Markdown Editor

System Design Document Template

System design at scale – requirements, capacity estimates (KaTeX), API, data model, HLD, deep dives, reliability, cost, trade-offs

Mode d'emploi: New services or major redesigns. Write requirements and capacity estimates before any diagram, keep every estimate as a formula with its inputs, and fill section 10 with the options you rejected – reviewers will ask. Replace the URL-shortener example numbers with your own.

Aperçu

System Design: [System or feature name]

Complete system design document for a service or platform at scale: requirements, capacity estimates, API, data model, high-level and detailed design, scaling, reliability, security, operations, cost and trade-offs. Replace every [bracketed] value and every value marked Example. Worked numbers use a URL-shortening service so the formulas stay concrete; swap in your own.

Document control

FieldValue
Document ID[SDD-SYSTEM-001]
System / feature[Name]
Version[0.1]
Status[Draft / In review / Approved / Implemented / Superseded]
Author(s)[@author]
Reviewers[@reviewer-1], [@reviewer-2]
Last updatedYYYY-MM-DD
Related[PRD / SRS], [Architecture description], [ADRs]

Approvals

RoleNameDecisionDate
Tech lead[@name][Approved / Changes requested]YYYY-MM-DD
Staff / principal engineer[@name][Decision]YYYY-MM-DD
SRE / operations[@name][Decision]YYYY-MM-DD
Security[@name][Decision]YYYY-MM-DD

Revision history

VersionDateAuthorChange summary
0.1YYYY-MM-DD[@name]First draft for design review
0.2YYYY-MM-DD[@name]Example: Switched ID generation to base62 counter ranges after review
1.0YYYY-MM-DD[@name]Example: Approved

Contents

1. Overview

1.1 Problem statement

[What problem exists today, who has it, and what it costs. Example: "Our marketing links are 120+ characters, break in SMS, and give us no click data."]

1.2 Proposed solution

[One paragraph. Example: "A stateless redirect service backed by a key-value store and a CDN, generating 7-character base62 keys from pre-allocated counter ranges, with click events streamed to the analytics pipeline."]

1.3 Decisions requested from reviewers

IDQuestionRecommended optionSection
Q-01Example: Counter ranges or hashing for key generation?Counter ranges7.1, 10
Q-02Example: Accept eventual consistency for click counts?Yes, up to 60 s lag7.3
[Q-nn][Question][Option][Section]

2. Requirements

2.1 Functional requirements

IDRequirementPriority
FR-01Example: Create a short link for a long URL, optionally with a custom aliasMust
FR-02Example: Redirect a short link to its long URLMust
FR-03Example: Expire links at an optional expiry dateShould
FR-04Example: Show click counts per link per dayShould
[FR-nn][Requirement][Must / Should / Could]

2.2 Non-functional requirements

IDQualityTargetMeasured as
NFR-01LatencyExample: Redirect p99 at or below 50 ms at the edgeEdge logs, rolling 5 min
NFR-02AvailabilityExample: 99.99% monthly for redirectsSynthetic checks
NFR-03DurabilityExample: No created link is ever lostBackup and restore drills
NFR-04ConsistencyExample: A new link redirects within 1 s of creationIntegration test
NFR-05SecurityExample: No open redirect to blocklisted domainsSecurity test suite
[NFR-nn][Quality][Target][Measurement]

2.3 Out of scope

  • [Example: link editing after creation]
  • [Example: user accounts beyond API keys]
  • [Item deferred, with the release that will take it]

3. Capacity estimation

3.1 Assumptions

InputSymbolValueSource
New links per monthNwN_wExample: 100 millionMarketing forecast
Read to write ratiorrExample: 100 : 1Comparable services
Average stored recordssExample: 500 bytesSchema in 5.2
RetentionYYExample: 5 yearsProduct decision
Peak to average factorkkExample: 3Traffic history

3.2 Throughput

Average write rate, with 2.6×1062.6 \times 10^6 seconds in a month:

QPSw=Nw2.6×106=1082.6×106≈40 writes/sQPS_w = \frac{N_w}{2.6 \times 10^{6}} = \frac{10^{8}}{2.6 \times 10^{6}} \approx 40 \ \text{writes/s}

Reads and peak:

QPSr=r⋅QPSw≈4 000 reads/s,QPSpeak=k⋅QPSr≈12 000 reads/sQPS_r = r \cdot QPS_w \approx 4\,000 \ \text{reads/s}, \qquad QPS_{peak} = k \cdot QPS_r \approx 12\,000 \ \text{reads/s}

3.3 Storage

S=Nw×12×Y×s=108×12×5×500 B=3 TBS = N_w \times 12 \times Y \times s = 10^{8} \times 12 \times 5 \times 500 \ \text{B} = 3 \ \text{TB}

With replication factor 3 the raw footprint is about 9 TB.

3.4 Bandwidth and memory

Bout≈QPSpeak×500 B≈6 MB/sB_{out} \approx QPS_{peak} \times 500 \ \text{B} \approx 6 \ \text{MB/s}

Caching the hottest 20% of daily read keys (Pareto assumption):

M=0.2×QPSr×86 400×s≈35 GBM = 0.2 \times QPS_r \times 86\,400 \times s \approx 35 \ \text{GB}

3.5 Key space

With base62 keys of length LL the key space is 62L62^{L}. For L=7L = 7:

627≈3.5×1012≫6×109 links in 5 years62^{7} \approx 3.5 \times 10^{12} \gg 6 \times 10^{9} \ \text{links in 5 years}

3.6 Summary

QuantityEstimateDesign consequence
Write rate~40/s averageA single partitioned store handles writes
Read rate~4 000/s average, ~12 000/s peakReads must be served from cache and CDN
Storage~3 TB logical, ~9 TB replicatedHorizontally partitioned key-value store
Cache~35 GBFits a small in-memory cache cluster
[Quantity][Estimate][Consequence]

4. API design

4.1 Endpoints

MethodPathPurposeAuthIdempotent
POST/v1/linksCreate a short linkAPI keyWith Idempotency-Key header
GET/{key}Redirect (302) to the long URLNoneYes
GET/v1/links/{key}Read link metadataAPI keyYes
GET/v1/links/{key}/stats?from=&to=Daily click countsAPI keyYes
DELETE/v1/links/{key}Disable a linkAPI keyYes

4.2 Request and response examples

Create a link. The Idempotency-Key header makes retries safe: the same key within 24 hours returns the original response instead of a second link.

POST /v1/links HTTP/1.1
Content-Type: application/json
Idempotency-Key: 7f9c2ba4-e88f-11ee-a951-0242ac120002

{"url": "https://example.com/campaigns/spring?utm_source=sms", "alias": null, "expiresAt": "2027-01-01T00:00:00Z"}
HTTP/1.1 201 Created
Location: /v1/links/aZ3kP9q
Content-Type: application/json

{"key": "aZ3kP9q", "shortUrl": "https://sho.rt/aZ3kP9q", "url": "https://example.com/campaigns/spring?utm_source=sms", "expiresAt": "2027-01-01T00:00:00Z"}

4.3 Errors

HTTP/1.1 409 Conflict
Content-Type: application/problem+json

{"type": "https://sho.rt/problems/alias-taken", "title": "Alias already in use", "status": 409, "detail": "The alias 'spring' belongs to another link.", "instance": "/v1/links"}
StatusProblem typeWhen
400invalid-urlURL is malformed or not http(s)
403blocked-domainTarget domain is on the abuse blocklist
409alias-takenCustom alias exists
429rate-limitedClient exceeded its quota; Retry-After is set

4.4 Rate limits and versioning

  • Rate limit: [Example: 100 creates per minute per API key, token bucket].
  • Versioning: path prefix /v1; breaking changes go to /v2 with a [12-month] deprecation window announced by the Deprecation header.

5. Data model

5.1 Entities

Logical entities and their keys. Physical types depend on the stores chosen in 5.2.

5.2 Storage choices

DataStorePartition keyMain queriesWhy
LinksExample: Distributed key-value storekeyGet by keySingle-key lookups at high read rate
Daily clicksExample: Wide-column or time-series storekey, dayRange by key and dayAppend-heavy counters
API keysExample: Relational databaseidGet by idSmall, transactional
[Data][Store][Key][Queries][Reason]

6. High-level design

ComponentResponsibilityScales by
CDN / edge cacheServe popular redirects close to usersProvider
Redirect serviceResolve key, emit click event, return 302Stateless replicas
Link API serviceCreate, read, disable links; enforce quotasStateless replicas
Key range allocatorHand out unique counter ranges to API instancesSingle leader, rarely called
Click aggregatorTurn click events into daily countsConsumer group partitions
[Component][Responsibility][Scaling unit]

7. Detailed design

7.1 Key generation

[Describe the algorithm. Example: each API instance leases a block of 1 000 000 counter values from the allocator, encodes the next value in base62 and pads to 7 characters. Leases are stored durably; a crashed instance wastes at most one block. Custom aliases are inserted with a conditional write that fails if the key exists.]

7.2 Redirect path

The redirect never waits for analytics: the click event is published asynchronously after the long URL is known, and a cache miss repopulates the cache for later requests.

7.3 Click counting

[Example: redirect instances publish click events without waiting; the aggregator consumes per partition, counts in memory for 30 s and adds the totals to the daily row. Counts may lag by up to 60 s and may over-count by duplicates on consumer restart; dashboards state this.]

7.4 Expiry and deletion

[Example: expiry is checked on read; a daily job removes expired links from the store and purges them from the CDN.]

8. Scalability and performance

ConcernApproachLimit before redesign
Read throughputCDN and in-memory cache absorb most reads; redirect service scales horizontallyExample: ~200 000 reads/s per region
Write throughputPartitioned key-value store; key ranges avoid coordinationExample: ~5 000 writes/s
Hot keysCDN caching with short TTL; request coalescing in the redirect serviceOne viral link at ~50 000 reads/s
Storage growthAdd partitions; expire old links[Limit]
[Concern][Approach][Limit]

Latency budget for a redirect cache miss (target p99 50 ms):

StepBudget
Edge to region network20 ms
Load balancer and service5 ms
Cache lookup2 ms
Key-value lookup on cache miss10 ms
Headroom13 ms

9. Reliability, security and operations

9.1 Failure modes

FailureImpactDetectionMitigation
Cache cluster downHigher latency, more store loadCache error rateFall through to store; store sized for full read load at reduced latency
Key-value store partition unavailableSome keys failError rate per partitionReplication factor 3, quorum reads
Event stream downClick counts lagConsumer lag alertRedirects never block on events; replay from buffer
Region outageFull outage in regionSynthetic checksActive-active in two regions with replicated store
[Failure][Impact][Signal][Mitigation]

9.2 Security and abuse

ThreatControl
Malicious target URLs (phishing, malware)Domain blocklist and URL reputation check at creation; periodic rescans
Key enumerationNon-sequential presentation of keys; rate limits on reads per IP
API key leakageKeys hashed at rest, per-key quotas, rotation endpoint
Data exposureTLS everywhere; minimal personal data; access logging
[Threat][Control]

9.3 Observability

SignalMetric or logAlert threshold
Redirect latencyp50, p99 per regionp99 above 50 ms for 10 min
Redirect errors5xx rateAbove 0.1% for 5 min
Cache hit ratioHits / requestsBelow 85% for 30 min
Click pipeline lagConsumer lag secondsAbove 120 s
[Signal][Metric][Threshold]

9.4 Cost estimate

ItemUnit costQuantityMonthly cost
Compute (redirect + API)[$/instance-month][n][$]
Key-value store[$/TB-month][9 TB][$]
Cache[$/GB-month][35 GB][$]
CDN egress[$/GB][GB/month][$]
Total[$]

10. Trade-offs and alternatives

DecisionOptionsChosenWhyWhat we give up
Key generationHash of URL; random keys with collision check; counter rangesCounter rangesNo collisions, no read-before-writeKeys reveal rough creation order unless shuffled
Redirect status301 permanent; 302 temporary302Every click reaches us for counting and disablingMore origin traffic than 301
Click countsSynchronous increment; async streamAsync streamRedirect latency unaffectedCounts lag up to 60 s
[Decision][Options][Chosen][Why][Cost]

11. Delivery plan and risks

11.1 Milestones

MilestoneScopeExit criterionTarget date
M1Create and redirect, single regionLoad test at 2x peak passesYYYY-MM-DD
M2Click counts and dashboardsLag below 60 s for 7 daysYYYY-MM-DD
M3Second region, active-activeRegion failover drill passesYYYY-MM-DD
[Mn][Scope][Criterion]YYYY-MM-DD

11.2 Rollout and rollback

[Feature flags, canary percentage, metrics watched during rollout, and the exact rollback steps.]

11.3 Risks

IDRiskLikelihoodImpactMitigationOwner
R-01Example: Traffic forecast is 3x too lowMediumHighLoad test at 5x; autoscaling limits reviewed[@name]
R-02Example: Abuse overwhelms blocklist processMediumMediumAutomated reputation service; manual review queue[@name]
[R-nn][Risk][L / M / H][L / M / H][Mitigation][@name]

12. Appendices

12.1 Open questions

IDQuestionOwnerDue
OQ-01Example: Do we need per-link analytics beyond daily counts?[@name]YYYY-MM-DD
[OQ-nn][Question][@name]YYYY-MM-DD

12.2 Glossary

TermMeaning
QPSQueries (requests) per second
p9999th percentile latency
TTLTime to live of a cached entry
Base62Encoding with digits, lowercase and uppercase letters
[Term][Meaning]

12.3 References

ReferenceUse
RFC 9110 HTTP SemanticsStatus codes and methods
RFC 9457 Problem Details for HTTP APIsError format in 4.3
[Internal ADR or document][Use]

Standard and licence note

Based on common industry practice for system design documents and on the HTTP standards cited in 12.3. Original text written for this collection; example numbers are illustrative. Template licence: MIT.

Modèles associés