In short. Keep one authoritative token-to-destination decision. Make retries identify the same creation, and bound cache reuse by the promised withdrawal behavior.
One table does not answer every contract
A table with token and destination is a reasonable beginning. It becomes insufficient when the design silently assumes that a read replica is current, every cache honors immediate withdrawal, and every redirect event reaches analytics exactly once.
Split requirements by consequence. Losing an analytics event changes reporting; assigning one token to two destinations breaks the link's identity. A stale destination after withdrawal has a different risk from a delayed dashboard count. These requirements should not share an accidental best-effort policy.
Begin with a modular service and one authoritative database if it meets the chosen workload. Separate mapping, authorization and analytics boundaries in the design without requiring independently deployed microservices. Extract a component when isolation, ownership or measured scaling requirements justify the distributed recovery burden.
Trace creation, redirect and withdrawal
Creation authenticates the owner, validates destination policy, assigns a candidate token and atomically inserts a unique mapping. A repeated creation attempt carries a stable operation identity. A conflicting token candidate is retried under a bounded allocation policy; the uniqueness constraint decides ownership rather than an optimistic precheck.
Redirect lookup checks the mapping's active state and returns the selected HTTP redirect semantics. RFC 9110 defines redirect status behavior; the service must choose intentionally rather than assuming all redirects have identical method and caching consequences.
Withdrawal changes authoritative state and records invalidation intent. Internal cache version checks prevent an older refill from replacing a newer withdrawn state. Browser or intermediary caching is a separate boundary governed by the actual response and cache semantics described in RFC 9111. Promise immediate withdrawal only if the complete served path can enforce it.
Northwind’s first mapping authority is a Postgres table with a unique token index. A Redis cache serves permitted reusable lookups; the creation transaction binds owner, request identity, destination and token. The public redirect path uses a narrow token lookup rather than the owner’s search interface. Administrative creation and withdrawal require authorization even when following an active public link does not.
Random token allocation needs both candidate generation and atomic uniqueness. A process cannot reserve a token by observing that it was unused a moment earlier. Let the unique insertion decide, then select another candidate after a confirmed collision within a bounded retry budget. The same request identity distinguishes collision recovery from a second user-created link when a response goes missing.
Additional toy allocation calculation. In the illustrative 100-value namespace, ten assigned values leave a collision probability of 10/100 = 0.1 for the next independent uniform candidate. Holding occupancy fixed for this one allocation, the probability of three successive collisions is 0.1³ = 0.001, or 0.1%. Success within those three attempts is 1 − 0.001 = 99.9%. Those are derived toy probabilities, not measured availability or a recommended production namespace. Bound attempts even when collision probability is small.
At the much larger 62¹⁰ namespace, occupancy fraction for one next draw is only one part of planning. Across many allocations, collision opportunities accumulate. Unpredictability, uniqueness and authority also remain distinct: an unguessable public token is not a substitute for authentication on destination edits, and uniqueness says nothing about whether a destination is abusive.
Derive the first capacity model
Hypothetical scenario. Choose 100,000 new mappings per day and ten million redirect requests per day. Mean creation demand is 100,000 ÷ 86,400 ≈ 1.16 requests per second; mean redirect demand is 10,000,000 ÷ 86,400 ≈ 115.74 per second. Choose a planning peak multiplier of ten for redirects, yielding approximately 1,157.4 per second. That multiplier is an assumption to validate, not an industry constant.
With a chosen logical mapping payload of 300 bytes and 365 days of retention, payload is 100,000 × 365 × 300 = 10,950,000,000 bytes, or 10.95 GB. Three full copies require 10.95 × 3 = 32.85 GB of that payload. Indexes, WAL, backups, allocation, deleted records and metadata are additional.
Choose a hypothetical cache hit fraction of 0.9. At the chosen redirect peak, lookup misses are 1,157.4 × (1 − 0.9) = 115.74 per second. During an empty-cache recovery they can approach the full 1,157.4, before retries and refill amplification. Size and admission decisions must consider that path, not only the warm-cache mean.
A ten-character token over an alphabet of 62 symbols has 62¹⁰ = 839,299,365,868,340,224 possible strings. This namespace size does not guarantee collision-free random allocation or confidentiality. For a separate toy namespace of 100 values with ten already assigned, a uniform next candidate collides with probability 10 ÷ 100 = 0.1. Always enforce uniqueness; use a suitable unpredictable identifier when enumeration is a concern.
Finally, choose 100 bytes of logical analytics payload per redirect. Ten million events produce 10,000,000 × 100 = 1 GB per day before stream and storage overhead. The reporting path can exceed mapping growth even though it is not authoritative business state.
In the wild: Bitly exposes more than a two-column mapping
Bitly’s official short-link tutorial separates basic shortening, custom domains and customized back-halves. Its operations carry group identity as well as the long destination. Its deletion documentation also distinguishes an unedited link from one whose destination or back-half has changed. These are public product and API contracts, not a description of Bitly’s internal database.
Northwind should likewise decide whether changing a destination preserves a token, what owner scope applies and which withdrawal promises are enforceable. Writing those rules before choosing a cache policy makes the architecture review concrete. A short string alone does not specify lifecycle, authority or the meaning of deleting a link.
The fast path must respect revocation
Cache immutable mappings aggressively only if immutability is the actual policy. A mutable destination or withdrawal requirement changes safe reuse. A cache lifetime can bound one layer's reuse while still allowing older source data to enter that layer, as the caching lesson demonstrated.
Destination validation is a policy boundary. Parse consistently, restrict supported schemes, and consider phishing and abuse response. Following arbitrary destinations server-side to generate previews creates a different network-access risk; keep that feature outside this design unless its fetching authority and isolation are specified.
Use one authoritative write boundary initially. Additional read regions require the consistency contract taught earlier: a replica's reachable state is not necessarily current enough for withdrawal. If an authoritative decision cannot be obtained, choose an explicit degraded behavior compatible with the product's risk.
A hot link arrives during cache recovery
Hypothetical scenario. A popular link is requested while caches restart. Every process attempts the same database refill. Meanwhile, an owner withdraws the link. A delayed refill returns the older active mapping after invalidation and tries to store it.
Coalesce refill work within a clearly stated scope, bound concurrent source lookups and use mapping versions to reject obsolete results. If processes coordinate only locally, estimate their combined refill pressure. A database that handled the warm path may not handle an uncontrolled cold burst.
Observe accepted creations, redirect outcomes, withdrawal visibility, source demand and analytics lag separately. Report unresolved invalidation work and define recovery ownership. A high redirect success ratio does not establish that withdrawn links stopped resolving correctly.
Common misconceptions: borrowing the wrong product contract
A chat system must define delivery, ordering and offline synchronization for messages. The URL service borrows the distinction between event acceptance and user-visible completion, but does not need presence or conversation fan-out.
A news feed makes fan-out and a popular publisher's demand central. Here a popular link creates a hot lookup key. Cache reuse can help, while an indivisible mutable record still needs one coherent authority.
A payment ledger requires accounting invariants beyond a redirect counter. Keep approximate or delayed analytics separate from any future billing ledger; importing the word event does not make reporting financially authoritative.
Video delivery moves large media objects and introduces encoding and playback concerns. This service redirects to a destination; it does not store or transcode that destination's content. An edge cache helps only within the link's actual revocation contract.
Typeahead adds prefix search and ranking. Public redirect lookup is an exact token lookup. If owners need destination search, make it an authorized derived index with declared freshness rather than burdening every redirect with ranking.
Geospatial matching needs location freshness and a matching policy. Link routing here selects a storage owner, not a nearby driver. Similar-looking routing diagrams do not imply equivalent state semantics.
Collaborative editing must reconcile concurrent operations on shared documents. This case can instead reject conflicting mapping changes through an expected version. Do not introduce OT or CRDT machinery when the product does not permit concurrent merge semantics.
State the evolution and rejected options
Start with a unique indexed mapping store, bounded lookup cache and asynchronous reporting. Reject premature sharding until a measured resource or isolation constraint requires it. Reject unbounded caching when withdrawal matters, and reject synchronous analytics on every redirect unless reporting's stronger completion requirement justifies that dependency.
If growth requires partitioning, select token-based placement for exact lookups and separately address owner listings. Retain authority and migration versions. If analytics must become loss-accounted, define durable event acceptance and its effect on redirect availability; do not claim the earlier best-effort path already met that requirement.
The design review deliverable is a set of explicit contracts and failure decisions, not a branded infrastructure diagram. Record which assumptions must be measured before provisioning and which user promises change if the fast path is unavailable.
What the redirect contract cannot promise
The capacity figures are hypothetical payload counts, not hardware limits. The service controls future authorized lookups and its own cache policy; it cannot erase a destination already delivered to a visitor. Abuse review, preview fetching and financially authoritative analytics need their own contracts. Choose the enforceable withdrawal window before promising immediate revocation across independent clients and intermediaries.
Final exercise: review the URL service
The owner now requires immediate withdrawal at every reader, including responses already cached by visitors. What must change in the promise?
Identify the unenforceable boundary: the service cannot retroactively remove an already delivered destination from a visitor. Define the enforceable future-request path, avoid unsupported cache promises, and explain any transition period from earlier cache policies. A product promise must reflect actual control.
Redirect analytics become billable. Can the existing asynchronous count be reused unchanged?
Not without a new accounting contract. Define eligible events, durable acceptance, duplicate handling, missing-event reconciliation and disputed counts. Decide whether redirects depend on accounting acceptance and state the resulting availability trade.
A single token dominates reads and the source saturates during restart. Is sharding the only next step?
No. Examine bounded refill, scoped coalescing, safe cache recovery and source admission first. More token-keyed shards do not divide one hot key. Measure the constrained path and preserve withdrawal semantics while choosing an intervention.
A token candidate collides after creation was authorized. Should the client generate a new operation identity?
No. Retry token allocation inside the same logical creation. A different token candidate does not imply a different user intention.
A 90% cache hit rate is observed, but withdrawn links still resolve. Did the cache meet its contract?
No. Hit rate measures reuse, not eligibility. Trace source revision, invalidation and intermediary cache policy against the withdrawal promise.
Northwind decision log
Separate link creation from the redirect read path.
Cache redirects while preserving deletion semantics.
Allocate identifiers independently from redirect latency.
Go deeper: token lookups and link lifecycle
- Video lecture: System Design: Design a service like TinyUrl — Tushar Roy. Watch first: compare the creation and redirect paths before adding storage components.
- Book chapter: Database System Concepts, 7th edition, chapter 14: Indexing — Abraham Silberschatz, Henry F. Korth and S. Sudarshan. Understand exact token lookups and unique index maintenance.
- Book chapter: Database System Concepts, 7th edition, chapter 15: Query Processing — Abraham Silberschatz, Henry F. Korth and S. Sudarshan. Separate lookup cost from owner listings and reporting queries.
- Primary source: Shorten & Customize Links — Bitly. Compare a real public link API with the stated creation and withdrawal promises.