Skip to content
Tech Interview Prep
Technical interview guide

URL Shortener Design

Designing a URL shortener: unique keys, redirect semantics, cache TTLs, click accounting off the GET path, and open-redirect abuse.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: HTTP per RFC 9110 and RFC 6585; UUIDs per RFC 9562; uniqueness illustrated with PostgreSQL unique indexes and Redis GET; abuse controls per OWASP and Unicode TR36.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain the mapping, not the hash and how it changes a production decision.

Answer

The mapping is the product: a row (key, long_url, owner, created_at, expires_at, status) with a unique index on key, plus a read path that resolves it. The hash is a function that can only mint a candidate key: it cannot revoke, re-point, or name a link. That distinction decides four production questions at once: how keys are generated, whether custom aliases are possible, how takedowns work, and how long you can cache.

verbpathstore opresponse
POST/v1/linksINSERT ... ON CONFLICT DO NOTHING201 {key, short_url}
GET/{key}SELECT long_url WHERE status='active' AND expires_at > now()302 Location + Cache-Control
DELETE/v1/links/{key}UPDATE status='gone'204

Key generation. Hash the URL and truncate to 6 base62 chars and you get 62^6 ≈ 5.7e10 keys. At 1e9 links the chance a fresh insert collides is n/N ≈ 1.7e-2: about 1.7% of writes hit the unique index and need a retry. At 7 chars (62^7 ≈ 3.5e12) it drops to 2.8e-4. So the hash does not remove the store; it moves the collision check into it. The decision: size the key from your expected key count, not from the digest's width.

Custom aliases. A user wants /acme-launch. A hash cannot produce it; the mapping can, with the same unique index plus a reserved-word denylist (/api, /admin, /health). This is the decision that most often flips a team from hash-derived to random-or-counter keys.

Takedown and re-pointing. A legal takedown or a marketing re-point is an UPDATE on the row. A hash-derived key is immutable by construction, you cannot un-mint it, so you need the mapping anyway.

Failure modes, with detection:

  • Collision retry storm. Key length too short means the insert path retries and latency climbs. Detect: count unique-violation errors per minute; alert when retries exceed ~0.1% of writes. Cost: each retry is an extra round trip (~1 ms local, 5–20 ms cross-AZ).
  • Alias shadowing. Someone registers /admin before the denylist ships. Detect: a write-time denylist check plus a synthetic probe that GETs reserved paths and expects 404. Cost: a route shadow that can 302 users off-site.
  • Stale negative cache. A 404 cached for a day means a key created a minute later still 404s. Detect: keep the negative TTL short (10 s) and the positive TTL long, and measure the miss-then-create gap. Cost: a link that works for its creator and 404s for everyone else.
  • Expiry not enforced on read. The SELECT must filter expires_at; a cache serving a 302 past expiry is a legal problem. Detect: a periodic job that GETs expired keys and expects 404.

Trade-off: hash-derived keys are idempotent. The same URL yields the same key, which dedupes and saves rows. Random keys are not, so you either accept duplicates or add a unique index on (long_url, owner). Counter keys are shortest and collision-free but leak volume and need a range allocator (allocate 10k IDs per node) to avoid one hot sequence.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

How would you reason about base62 encoding of a counter in a system you own?

Answer

Start with the one decision that determines everything else: does the key need to hide creation order? A base62 encoding of a monotonic counter is short, collision-free by construction, and leaks the order and approximate creation time of every row. If that leak is acceptable (internal IDs, log correlation, shard-local keys) encode the counter and stop. If it is not, allocate the counter first and then permute or encrypt it. Do not reach for a random string, which trades a guarantee for a probability.

The arithmetic. The alphabet 0-9A-Za-z is 62 symbols. 62^6 = 56,800,235,584 (~5.7e10); 62^7 = 3,521,614,606,208 (~3.5e12). A full 64-bit counter (max 1.8e19) needs 11 characters, since 62^10 ≈ 8.4e17 and 62^11 ≈ 5.2e19. Length grows logarithmically: the 10-billionth key is 6 characters, the 10-trillionth is 8.

The encoder, traced.

Python
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

def b62(n: int) -> str:
    if n == 0:
        return ALPHABET[0]
    out = []
    while n:
        n, r = divmod(n, 62)
        out.append(ALPHABET[r])
    return "".join(reversed(out))

Trace: b62(0) → "0". b62(61) → divmod(61,62)=(0,61) → 'z' → "z". b62(62) → (1,0)→'0', then (0,1)→'1', reversed → "10". b62(3843) → (61,61)→'z', (0,61)→'z' → "zz". b62(3844) → (62,0)→'0', (1,0)→'0', (0,1)→'1' → "100". So 62^2−1 is the last 2-character key and 62^2 is the first 3-character key: the boundary is exact, no padding needed.

Where the reasoning goes wrong.

scheme6-char spacefirst expected collision
base62(counter)5.7e10never, until the counter wraps
random 6-char5.7e10~2.4e5 inserts (birthday)
sha256[:6] of URL5.7e10same birthday, plus same-URL duplicates

Claiming a 6-character hash of a long URL is unique because 62^6 is large ignores birthday collisions, which start mattering around sqrt(N) ≈ 238,000 keys. Casual testing hides it because the input distribution, the ordering, or the scale that would expose it is exactly what a quick check leaves out.

Failure modes to name.

  1. Birthday collisions if you hash instead of count: see the table above.
  2. Case-insensitive storage. MySQL 8.0's default utf8mb4_0900_ai_ci collation treats 'a' and 'A' as equal, so a base62 key in a VARCHAR under that collation can collide in a unique index. Store as VARBINARY or use a case-sensitive collation.
  3. Single-writer bottleneck. A central counter is a serialization point; at high insert rates it becomes the throughput ceiling. Snowflake-style IDs (timestamp | machine id | sequence) or UUIDv7 (RFC 9562) remove it at the cost of 64-bit or 128-bit keys.

When not to use a base62 counter. Multi-region writes where no single allocator is reachable; keys exposed to users where order leakage matters; any system that needs global uniqueness without coordination. Base58 (drops 0, O, I, l) is the variant to pick when keys are read aloud or typed by hand.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

What does collision handling on insert guarantee, and what does it deliberately leave open?

Answer

The guarantee. A unique index makes "does this key exist?" and "insert this key" one indivisible step at the storage layer. Of N concurrent inserts of the same key, exactly one commits; the rest fail with a duplicate-key error: SQLSTATE 23505 in PostgreSQL. That is the whole guarantee: mutual exclusion on the key, enforced by the index, not by your application.

What it deliberately leaves open. Everything after the failure. The store does not say which writer wins, does not generate a replacement key, does not retry, does not bound the retry, and cannot distinguish "the same logical request arriving twice" from "two different requests that happened to pick the same key." Uniqueness is guaranteed; progress and idempotency are not.

Why an application-level check cannot provide it. SELECT ... WHERE public_key = $1 followed by INSERT is two statements with a gap between them. Both writers read a miss, both insert, both commit: two rows, one key. The index closes the gap because the B-tree insert serialises on the key's index tuple: the second inserter blocks until the first transaction commits or aborts, then rechecks and raises 23505.

Trace, two concurrent inserts of key k:

twriter Awriter Bindex
1INSERT ktuple k uncommitted
2INSERT kblocks on A's tuple
3COMMITk committed
4recheck fails → 23505
5INSERT k2succeeds

Step 2–3 is the part people miss: B waits for the duration of A's transaction, not for the insert. A 200 ms transaction is a 200 ms stall for every colliding writer.

Choosing between the two conflict actions. The criterion is whether the key is derived from the request or random.

  • Random key, different destinations: ON CONFLICT DO NOTHING RETURNING. Zero rows back means the key was taken, so generate a new one and retry, bounded (5 attempts is generous). With a 62-character alphabet and 7 characters the keyspace is 62⁷ ≈ 3.5 × 10¹²; at 10 M live keys the per-insert collision probability is ≈ 2.8 × 10⁻⁶, so a retry is rare and one retry is almost always enough.
  • Deterministic key (same owner + destination hashes to the same key): ON CONFLICT DO UPDATE SET public_key = EXCLUDED.public_key RETURNING *. A no-op update that returns the winner's row, making the request idempotent. It writes a new row version and takes a lock, so it is the wrong choice on a hot key.
SQL
-- PostgreSQL 16
CREATE TABLE links (
  public_key text PRIMARY KEY,      -- the unique B-tree index
  owner_id   bigint NOT NULL,
  target_url text   NOT NULL
);

-- random key: claim it, or learn it is taken
INSERT INTO links (public_key, owner_id, target_url)
VALUES ($1, $2, $3)
ON CONFLICT (public_key) DO NOTHING
RETURNING public_key;   -- 0 rows => retry with a fresh key

Failure modes.

  • A long transaction holding the key stalls every colliding writer. Detect with pg_stat_activity where wait_event_type = 'Lock' and wait_event = 'transactionid'.
  • Unbounded retry on a hot key becomes a thundering herd. Bound attempts and fall back to a longer key or a sequence.
  • A read replica serving a stale miss: the application-level check passes, the insert fails at the primary. Route the insert to the primary.
  • Partitioned table: a unique index on a partitioned table must include the partition key, or uniqueness holds only per partition. Sharding by key prefix has the same hole unless routing is deterministic.

Scope. The guarantee is per index, per database, on the primary. It says nothing about the key space being large enough, about fairness between writers, or about what the client sees on the losing path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How would you explain partitioning the map without using the usual slogan?

Answer

The map is key -> long_url. The read path is a point lookup: GET /{key}. So the partition key has to be the key you look up with, and everything else follows from that.

Concretely: shard = hash(key) % N, or a directory service mapping key ranges to shards. A POST generates a key (base62 of a counter, or a random 7-char string), writes (key, long_url) to shard(key). A GET computes the same hash and hits one shard. One round trip, ~0.5 ms in-datacenter, O(1).

shard byPOST duplicate URLGET /abccost
hash(key)may land on another shardone shard1 lookup
hash(long_url)same shardunknown shardfan-out to all N
range on sequential idlatest shardone shardwrite hotspot

Why hash(long_url) is the trap: it makes duplicate detection cheap (same URL, same shard, local unique index) but the key no longer determines the shard. GET /abc has to ask every shard. At 64 shards that is 64 connections per read; even issued in parallel, p99 is bounded by the slowest shard, and one slow shard stalls the request. Serially it is 64 × 0.5 ms = 32 ms.

Range on a monotonic counter: the newest shard absorbs 100% of writes. With 64 shards you are using 1/64 of write capacity and 63 shards sit idle for writes. You split when the hot shard crosses a threshold, say 50 GB or 5k writes/s, but the split is itself a migration.

Modulo vs consistent hashing: hash % N remaps (N-1)/N of keys when N changes. 63/64 ≈ 98% at N=64. Consistent hashing or a directory moves ~1/N ≈ 1.6%. If you expect to resize, pay for the directory or the ring up front.

Dedup stays out of the shard function. A secondary index on hash(long_url) (a separate table, or an async job that scans and merges) handles "same URL, different key". It is allowed to be eventually consistent; the shard function is not.

Failure mode to watch: a GET that touches more than one shard. Instrument fan-out per request and alert on any GET with fan-out > 1. Load test with a skewed key distribution (Zipf, not uniform): uniform keys hide the hotspot the happy path never shows.

The partition key is a correctness decision, not a tuning knob. Pick the key that makes the read path a point lookup, then measure shard count and split thresholds against your actual write rate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Teach the read path latency budget to an engineer who has only seen it as a rule of thumb.

Answer

Pin the assumption first. "Read path" here means one keyed lookup returning one small response, no aggregation: a URL shortener's GET /{key} answering 302 with a Location header. If your read joins tables or fans out to other services, this budget doesn't transfer: the fan-out is the budget.

The 60-second answer. The budget isn't a number, it's a count of round trips on the critical path. For a keyed lookup that's one cache RTT plus whatever the edge costs you. Same-AZ RTT is a few hundred microseconds; a Redis GET adds sub-millisecond server time. So the application's own work stays under 1 ms and everything else is network. p99 lands in the low tens of milliseconds, and almost all of that is the client's network and TLS, not your service.

Illustrative figures, 50k redirects/s, single region:

hopp50p99what sets the tail
edge TLS + 3028 ms25 msnew-connection handshakes, client RTT
Redis GET, same AZ0.4 ms2 mssingle-threaded server, a slow command ahead of you
Postgres primary, on miss3 ms40 mscheckpoint, lock wait, buffer miss
join to click totals on GET12 ms180 msscan size grows with traffic

Why the p99 isn't the sum of the p99s. The hops are independent, so the tail of the total is dominated by whichever hop has the heaviest tail, not by adding them up. Two tail events you can't design away: a new TCP connection that loses its first packet waits the initial RTO (1 s per RFC 6298, floored at 200 ms in Linux) and a TLS 1.3 handshake costs an extra RTT before the first byte. That's why the edge row's p99 is 25 ms while its p50 is 8 ms, and why connection reuse (keep-alive, HTTP/2) buys more than any micro-optimization in the handler.

The budget is also a concurrency budget. Every millisecond of latency is in-flight requests you have to hold. Little's law: L = λW. At 50k rps and 3 ms per miss query, you need 5,000 × 0.003 = 15 queries in flight on average; a 20-connection pool runs at 75% utilization. The pool's ceiling is 20 / 0.003 ≈ 6,700 queries/s. If a checkpoint pushes query time to 10 ms, the ceiling drops to 2,000/s while 5,000/s keep arriving: the pool saturates and wait time grows without bound. The pool converts a database slowdown into an unbounded queue, which is why you alert on pool wait time, not just query time.

Where it breaks. Joining owner, tags and click totals onto every GET puts analytics on the user-visible path: 180 ms p99 against 2 ms. And a cache miss storm: Redis doesn't coalesce concurrent misses, so one hot key expiring sends every concurrent request to Postgres. Collapse them in the application:

Go
var g singleflight.Group

func lookup(key string) (string, error) {
    v, err, _ := g.Do(key, func() (any, error) {
        return loadFromDB(key) // one query per key; concurrent callers share it
    })
    if err != nil {
        return "", err
    }
    return v.(string), nil
}

How you'd catch it. Span the cache call and the database call separately. An aggregate p99 tells you something moved; per-hop spans tell you which hop. Watch cache hit rate and pool wait time as first-class metrics.

What to build. Serve Location from a key-value cache, write clicks asynchronously off the read path, keep the handler to one lookup plus one cache RTT. Then the budget is a property of the cache and the network, and every number in it is defensible.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

A teammate proposes a design that hinges on 301 versus 302 versus 307. How do you evaluate it?

Answer

What I'd say first

Two questions decide this, and neither is "which code is better". First: is the mapping immutable, or can someone repoint it. A rename, a takedown, an A/B switch? Second: does the request carry a method and body that matter, or is it a GET?

If the mapping can change, the answer is 307 (or 302 for a GET-only mapping). If it is genuinely immutable, 301 or 308 is fine and cheaper. The status code alone doesn't decide how long a wrong answer persists: the Cache-Control on the redirect response does.

What each code actually guarantees

codepermanencemethod/body on followheuristically cacheable
301permanentUA may rewrite POST→GETyes
302temporaryUA may rewrite POST→GETno
307temporarypreservedno
308permanentpreservedyes

Two columns are load-bearing. The method column for 301/302 is a permission, not a guarantee: RFC 9110 §15.4.2 and §15.4.3 say the user agent MAY change POST to GET. So you cannot rely on the body surviving, and you cannot rely on it being dropped either; clients differ. If the request is a POST with a body, 301/302 is a coin flip on whether the body arrives. 307/308 remove the ambiguity.

The cacheability column is why 301 is attractive: a permanent redirect is cached, so after the first hop the client goes straight to the destination with no extra round trip. A 302 costs a round trip every time. That is the real trade-off: you are buying latency with the ability to change your mind.

The failure this design invites

A cached permanent redirect that outlives the mapping. Worked example, explicit headers:

  • t=0: client GETs /old, gets 301 Location: /new-a, Cache-Control: public, max-age=86400.
  • t=60s: owner repoints /old → /new-b in the DB.
  • t=60s to t=86400s: the client that cached at t=0 never revalidates. It keeps going to /new-a. The DB change is invisible for up to 86,400 s.

Swap the status to 302 and the header to private, max-age=60 and the same client picks up /new-b within 60 s. Even with no Cache-Control at all, 301/308 get heuristic freshness: the window is not zero and not under your control. So if you ship a permanent redirect, ship an explicit Cache-Control with it.

The method failure is separate and quieter: a form POSTs to /checkout, the server answers 302 with Location: /checkout/confirm, the browser follows with GET and drops the body. The confirm page renders with no order data. It passes casual testing because the tester used a GET.

What I'd ask in the review

  • Is the mapping immutable, and who can change it? If anyone can, 301/308 needs a justification.
  • Is the request a GET? If not, 307/308.
  • What Cache-Control is on the redirect response? If it is absent on a 301/308, that is the bug.
  • Is the redirect on a path that also serves content, or on a host-level rule? Host-level 301s hurt most, because they are cached across every path.
  • For a public site, Google's redirect documentation treats 301/308 as permanent and 302/307 as temporary for ranking consolidation. That is a real reason to want 301, but it does not override a mutable mapping.

Verdict

Default to 307 for anything mutable or anything with a body; 302 only for a GET-only mutable mapping where you want the older code. Reserve 301/308 for mappings you can commit to, and pair them with an explicit Cache-Control so a future change has a bounded blast radius. Prefer 308 over 301 when the method matters: it has been in the spec since RFC 7538 and is widely supported now.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

How do you decouple real-time click tracking and analytics from the critical redirect read path to prevent latency degradation?

Answer

Redirect latency must depend solely on the key lookup, never on click accounting. Inline database increments or synchronous event publishing turn high-throughput reads into an operational write bottleneck.

Mechanically, separate the user response from the telemetry stream via fire-and-forget local batching or an out-of-process tailer:

Client ---> [Edge / Go Router] --- (1. Cache/DB lookup) ---> Fast 302 Found
                  │
                  ├── (2. Non-blocking local ring buffer or memory channel)
                  ▼
           [Local In-Memory Batcher]
                  │
                  ├── (3. Batched Flush: 50ms or 1,000 events)
                  ▼
           [Distributed Log (e.g., Kafka / Kinesis)]
                  │
                  ▼
           [Stream Aggregator (Flink / Worker Pools)] ---> (Aggregated Writes) ---> Analytics Store

Critical Path vs Asynchronous Path

  1. Synchronous Read Phase (Budget < 5 ms p99):

    • Lookup short key in local memory (Redis string or local in-process LRU cache).
    • Issue HTTP 302 Found with Location: <destination> per RFC 9110 and Cache-Control: private, no-store (or short TTL per RFC 5861) to guarantee subsequent clicks hit your router rather than client caches.
    • Emit click context (timestamp, IP hash, user agent, referer, link ID) onto a non-blocking bounded queue (e.g., Go buffered channel or RingBuffer).
  2. Decoupling Layer & Backpressure Trade-offs:

    • If the local buffer is full (e.g., during downstream Kafka partition leader election or network partition), the redirect worker must drop telemetry rather than block redirect I/O. A dropped metric is an analytics error; a blocked redirect is a critical site outage.
    • Background workers drain the ring buffer, batching hundreds of records into snappy-compressed payloads pushed to an append-only distributed event stream.
  3. Aggregation Phase:

    • Aggregation workers (e.g., stream processors using tumbling windows or Redis INCRBY batching via Redis strings) calculate click totals over 10-second intervals per short key.
    • Only aggregated metrics write back to durable primary tables (e.g., PostgreSQL with unique indexes on (link_id, time_bucket)), reducing write volume to the database by 99%.

Failure Mode Comparison

Pipeline Patternp99 Redirect ImpactPartition BlamabilityBackpressure Behavior
Sync DB UPDATE links SET clicks = clicks + 1Degrades from ~5ms to >150ms under load; lock contention on hot keysHigh (DB connection pool exhaustion directly crashes read path)Rejects redirects with 500/503
Synchronous Broker Produce (acks=all)Degrades to 20–80ms over network; spikes on broker GC pausesModerate (message queue saturation cascades to web workers)Blocks HTTP workers unless strict 10ms timeout applied
Non-blocking In-Memory Queue + Batch PublisherZero impact (< 1ms read overhead)Fully isolated (broker downtime does not touch redirects)Drops click events gracefully under overload (fails open)

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How would you test a claim that the system depends on negative caching?

Answer

"Depends on negative caching" is a claim you can falsify: turn negative caching off and see whether a metric you care about moves past its budget. If nothing moves, the system has negative caching enabled, not a dependency on it. So the test is a controlled removal, not reading the config.

State the assumptions first: which layer holds the negative entry (CDN edge, app Redis, DB plan cache), what key it is stored under, and which metric defines "depends". Origin request rate, origin p99, error rate, or egress cost. Pick one before you run anything.

Worked example, hypothetical numbers. A link shortener serves 5,000 rps of GET /:slug; 30% are negative lookups (unknown slugs, scanners, deleted links). Negative TTL is 15 s. Take one POP carrying 5% of traffic: 250 rps, 75 rps of them negative. At that POP roughly 5 distinct unknown keys arrive per second, so a 15 s window collapses 75 rps of lookups into 5 origin fetches per second.

stepactioncanary origin negative-lookup QPSorigin p99origin CPU
0baseline, negative TTL 15 s59 ms12%
1canary POP negative TTL → 07588 ms61%
2restore TTL 15 s59 ms12%

Interpretation: the 15× jump in origin QPS and p99 crossing from 9 ms to 88 ms is the dependency. Had step 1 left origin QPS flat and p99 inside budget, the answer is "it's enabled, it isn't load-bearing", and you say so.

Two things make this test lie. Run it at peak, not at 03:00: the dependency is load-dependent, and a quiet window gives a false negative. And run it for several TTL windows, because a single 15 s sample can be absorbed by connection pooling and look harmless.

The second variant separates load dependency from correctness dependency. Keep TTL at 15 s but skip the delete-on-create: a POST creates a slug, the negative entry for that key survives, and a GET from another POP returns 404 for up to 15 s. That failure is a dependency on invalidation, not on caching, and the two get conflated if you only ever test TTL=0.

Failure modes to name: disabling negative caching also disables the invalidation path, so a single experiment cannot attribute the break; a single-POP canary misses cross-POP behaviour; and the test itself adds origin load, so watch for the origin degrading for reasons unrelated to the cache.

What you do with the result: if it is load-bearing, the negative TTL is a capacity parameter. Size it against origin headroom, not against how stale a 404 feels. If it is not, shorten it or drop it and simplify the invalidation path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

What would you measure before treating idempotent create as settled?

Answer

Before I'd call idempotent create settled, I'd measure four numbers, because the design is a claim and these are what falsify it.

Assumptions I'd state first: the default mode is reuse-if-exists, keyed on (owner_id, destination_hash); always-new is opt-in per request. Clients retry on timeout with the same Idempotency-Key. Key records have a TTL.

What to measureHowSettled when
Duplicate-create rateSELECT owner_id, destination_hash, count(*) FROM links GROUP BY 1,2 HAVING count(*) > 1 over a weekzero rows in reuse mode; non-zero only where always-new was requested
Replay hit ratecounter on the key lookup: hits ÷ POSTstracks the retry rate you see in client logs; near-zero hits with zero duplicates means retries never reached you
TTL vs retry windowp99.9 of (last retry − first attempt) from client logs, against the key TTLp99.9 retry delay is orders of magnitude under the TTL
Unique-violation countcounter on the unique index over idempotency_keynon-zero under concurrency is fine; each one must resolve to a replay, not a 500

The fourth is the one people skip. Two concurrent requests with the same key both miss the lookup, both try to insert; the unique index rejects one. If that rejection surfaces as a 500, the client retries and you've manufactured the duplicate you were preventing.

Now the timeout case, and what each metric reads off it:

attemptkeyDBresponsemetric effect
1k-9finsert abctimeout, 201 lost—
2k-9flookup hit201 abcreplay hit +1, duplicates 0
2noneinsert def201 defduplicate-create +1 for the pair, abc orphaned

The orphan is the failure the question is really about: the client's copied URL points at abc, which nothing references. Measure it directly, links rows with no matching success entry in the access log, and it should be zero.

Cost metrics come after correctness: p99 added by the key lookup, and idempotency-table rows/day against TTL cleanup lag. Those decide whether the record lives in Postgres or moves to Redis with a shorter TTL; they don't decide whether the guarantee holds.

Failure modes to watch: a replay hit rate of zero alongside a duplicate rate of zero usually means your test traffic never retried. The happy path hides it. A TTL shorter than the p99.9 retry delay turns a slow client into a duplicate. A unique violation logged as an error rather than handled as a replay does the same.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How does read-your-writes after create change if the workload grows by two orders of magnitude?

Answer

Short answer: At 1x, read-your-writes after create is a routing problem. Send the creator's next GET to the primary, or wait for replica lag to drop. At 100x it stops being a routing problem and becomes a capacity problem: the primary can't absorb the redirected reads, and replica lag stops draining. The mechanism that survives is the one that removes the read entirely: return the key and its destination in the 201 response so the creator never has to GET.

Assumption: the creator is one of many clients, and creator read-after-write is a small fraction of total reads (I use 1% below). If that fraction is much higher, the redirect approach fails even sooner.

Why the redirect approach breaks

Illustrative arithmetic, not measured: baseline 1k writes/s, 10k reads/s, 1% of reads are creator read-after-write → 100 reads/s hitting the primary. The primary is sized for writes plus headroom, so this is free.

At 100x: 100k writes/s, 1M reads/s, still 1% → 10k reads/s to the primary. The primary now serves 10x its write volume in extra reads. That's the first wall.

The second wall is lag. Replica apply is often single-threaded per schema. If apply capacity is fixed and write rate goes up 100x, lag doesn't grow 100x: it grows until it saturates, and if writes outrun apply it never drains. The "route to primary for 2 seconds" window was sized against 400 ms lag; at 100x the lag may be 10 s and climbing, so the window is unbounded.

These two compound: more creator reads on the primary → more contention → slower writes → more lag → longer primary window → more primary reads.

What actually scales

mechanismcost per creator readat 100x
201 body carries key0 extra readsunchanged
route to primary N s1 primary readprimary read amplification, feedback loop
wait for lag < SLA1 blocked requestlag may never drain
write-through local cache1 cache write, must land on same serverfleet grows, hit rate drops
read token (LSN)1 replica read, blocks only creatorscales, needs replica wait support

The 201-body approach is O(1) in fleet size and write rate: the creator already has the answer, so there's no read to route. That's the one to reach for first.

If the client genuinely must re-read (it needs server-computed fields, say), the scaling fallback is a read token: the 201 returns the write's LSN or commit timestamp, and the creator's next GET carries it; the replica blocks until it has applied past that point. Only the creator waits, and only until its own write is visible, not until global lag clears. That is what survives 100x where "wait for lag < SLA" does not.

Failure modes

  • Duplicate POSTs: creator GETs a lagging replica, sees 404, retries the create. Detect by counting POSTs with identical idempotency keys per second; at 100x this shows up as a write-amplification spike, not a latency spike.
  • Primary read saturation: p99 on writes climbs because reads are stealing IO. Detect by splitting primary read vs write latency on the same dashboard.
  • Unbounded lag: replica lag trends up and never returns to baseline. Detect by alerting on the lag derivative, not the lag value.

The design decision at 100x is not "which routing trick": it's "can I avoid the read." If yes, the problem disappears. If no, the token approach is the only one whose cost stays proportional to the creator's own traffic.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

What trade-off does key alphabet and copy-paste force that a junior answer usually skips?

Answer

The trade-off is transcription robustness against density, and copy-paste is the switch that decides which side you want. A restricted alphabet (Crockford base32, 32 symbols, no I, L, O or U) costs you 18% more characters for the same entropy: 26 characters for 128 bits versus 22 in base62. You pay that in every URL, log line and index entry. What you buy back is a human reading a key off a label or a screen and typing it correctly. If keys only ever move by copy-paste, you bought nothing.

The part a junior answer skips is that the alphabet is a one-way door. The moment a key is printed on packaging, read aloud on a support call, or handed to a customer, the alphabet is a public interface. Changing it later doesn't just change new keys; it strands every key already in the wild.

Why misreads happen: the confusable pairs differ by one stroke or a closed versus open loop. 0/O, 1/I/l, 5/S, 2/Z, 8/B. A misread is a substitution, and a substitution in an opaque identifier is a lookup miss, not a near-miss. There is no checksum unless you add one, which is why Crockford's spec also defines an optional check symbol: it turns a misread into a detectable error instead of a wrong lookup.

alphabetsymbolsbits/charchars for 128 bits
base62625.9522
base58 (Bitcoin)585.8622
base36 (case-folded)365.1725
Crockford base32325.0026

Crockford's decoder repairs the common substitutions rather than rejecting them:

Python
ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"   # 32 symbols, no I L O U
DECODE = {c: i for i, c in enumerate(ALPHABET)}
DECODE.update({"I": 1, "L": 1, "O": 0})          # repair common misreads

def decode(s):
    return [DECODE[c] for c in s.upper().replace("-", "")]

decode("ab0cd") and decode("abOcd") both return [10, 11, 0, 12, 13]: O maps to 0, so the misread is silently corrected. decode("abUcd") raises KeyError: U is excluded from the alphabet and not repaired, deliberately, to keep accidental obscenity out of generated keys.

Three failure modes, with how you catch them and what they cost:

  1. Alphabet change after keys are printed. Old keys stop resolving. Detect it as a step change in "invalid key" responses on the key route, segmented by key length or prefix: a bare key gives you no other signal, because base32 and base62 overlap on digits and most uppercase letters, so you cannot tell which alphabet a key came from by looking at it. Length is a weak signal that only holds until you change the length too. Cost: either a decoder that accepts both alphabets forever, or a mapping table from old to new for every key ever issued, which grows without bound.

  2. Case-folding on input. If you generate base62 keys but some hop in the paste path uppercases or lowercases, the effective alphabet is 36, not 62: 5.17 bits per character instead of 5.95, and two distinct keys can normalize to the same string. At 22 characters the collision probability is negligible, but the damage isn't a collision: it's that a lookup returns the wrong record instead of a miss, and a miss is detectable while a wrong record is not. Detect it by enforcing uniqueness on the normalized form at generation time.

  3. Homoglyph paste. A key copied out of a PDF can carry a Cyrillic а (U+0430) or a smart quote. The decoder rejects it. Detect via input-validation error rate; the cost is a support ticket, because the user cannot see the difference.

Choosing: if a human ever transcribes the key, take the restricted alphabet and pay the 18%. If keys are machine-only, take base62 and spend the characters elsewhere. Either way, freeze the alphabet before the first key leaves your system, and if you must change it, version with a prefix rather than mutating existing keys.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Describe custom aliases and the evidence you would collect before relying on it.

Answer

Assumptions first. The system is a multi-tenant product where a user picks a handle that shows up in URLs (/u/<alias>), @-mentions, and API paths. The alias is a display string; the durable identity is a separate public_key (UUID). Everything below assumes you can change the alias string without changing identity, if the alias is the primary key, the trade-offs shift.

The core answer. An alias is a user-chosen string that must be (1) unique, (2) safe to render and route, (3) stable enough that links don't rot. You get those by restricting input to a documented alphabet, normalizing before you store and compare, and enforcing uniqueness in the database rather than in application code.

Concretely: accept [a-z0-9_-] after case-folding, length 3–32, reject anything that collides with a route or a reserved word, and store both the raw string (for display) and a normalized alias_key (for uniqueness). The unique index goes on alias_key.

Python
# Python 3.12
import unicodedata, re

ALLOWED = re.compile(r"^[a-z0-9_-]{3,32}$")

def alias_key(raw: str) -> str:
    folded = unicodedata.normalize("NFKC", raw).casefold()
    if not ALLOWED.match(folded):
        raise ValueError("alias outside allowed alphabet")
    return folded

Evidence to collect before you rely on it. This is the half of the question that decides the design, so name it:

  1. Normalizer idempotence and stability. Property-test alias_key(alias_key(x)) == alias_key(x) over a generated corpus. If it isn't idempotent, two spellings of the same alias slip past the unique index.
  2. Homoglyph corpus. Run the Unicode UTS #39 confusables table against your accepted set and assert no two distinct accepted aliases share a confusable skeleton. This is what catches аррle (Cyrillic а, р) vs apple.
  3. Uniqueness under concurrency. Fire N parallel inserts of the same alias and assert exactly one commits. A SELECT then INSERT in application code passes single-threaded tests and fails here.
  4. Reserved-word and route collision. Enumerate every route in the router and every reserved word, and assert none is a valid alias.
  5. Lookup latency at scale. p99 for alias→key resolution at your real row count; a unique index on a normalized column behaves differently from one on a raw string.

Alternatives, and when to pick them.

schemewhat it buyswhat it costs
ASCII-only [a-z0-9_-]trivial to reason about, no confusablesrejects legitimate non-Latin names
NFKC + script restrictionmost of the safety, keeps some Unicodeneeds the confusable corpus and a Unicode-version pin
IDN / punycode encodinground-trips any Unicode namedisplay vs. wire form diverge; still needs confusable checks

Pick ASCII-only when the alias is a routing key and users can set a separate display name. Pick normalized Unicode when the alias is the name users are known by.

Failure modes. Accepting any UTF-8 string because "the database is UTF-8" produces /аррle phishing that survives casual testing: the happy path hides it. Case-folding without a folded unique index lets Alice and alice both exist. A Unicode upgrade that changes normalization silently splits existing aliases; detect it by pinning the Unicode version and re-running the corpus on upgrade.

Decision path. If the alias is a routing key, ASCII-only plus a display name. If it's the user's identity, normalized Unicode with the confusable corpus in CI. Either way, uniqueness lives in the database, and the evidence above is what you run before you trust it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Where does open redirects matter, and where is it irrelevant?

Answer

Core answer

Open redirect matters when two things hold at once: the attacker controls the redirect destination, and the redirecting origin carries trust that a victim's browser, mail filter, or identity provider will act on. Break either condition and the finding is noise.

Where it matters

  • OAuth/OIDC. The IdP validates redirect_uri against a registered host and sends the authorization code there. If that host has an open redirect, the code lands on the trusted host and is immediately forwarded to the attacker. Same shape for SAML RelayState and for implicit-flow tokens carried in the fragment.
  • Password reset and magic links. The mail gateway and the user both trust yourapp.example. An open redirect turns your domain into a link-laundering service: the phishing URL arrives with your SPF/DKIM reputation and survives link rewriting.
  • Any origin with session cookies, or that appears in someone else's allowlist. A redirect on auth.example is worth more than one on static-cdn.example, because the first is on the trust path and the second is not.

Where it's irrelevant

  • The destination isn't attacker-controlled. A server-side constant, a relative path, or an ID looked up in a server-side table (/go/42 → row 42) gives the attacker no choice. There is nothing to redirect to.
  • The origin has no trust value. An internal-only host behind the VPN, with no auth cookies, not used for email, and not named in any allowlist, is a redirect nobody can weaponise. The bug exists; the impact doesn't.
  • The only reachable victim is the attacker. A post-authentication redirect whose target is chosen by the authenticated user harms nobody but that user.
  • Exact-match allowlist of one host. If the code compares the parsed hostname against a single literal, no attacker-selected destination is left.

The deciding table

ConditionMattersIrrelevant
Destination sourcerequest param, header, or DB row written by a userconstant, relative path, server-side ID map
Origin trustemail/SSO/OAuth path, session cookiesinternal-only, no cookies, not in any allowlist
Victima third partythe attacker themselves

Safe pattern (Python 3.12, urllib.parse)

Python
from urllib.parse import urlsplit

ALLOWED_HOSTS = {"good.example", "app.good.example"}

def safe_target(raw: str) -> str | None:
    p = urlsplit(raw)
    if p.scheme != "https":
        return None
    if p.username or p.password:          # https://trusted.example@evil.example
        return None
    if p.hostname not in ALLOWED_HOSTS:   # exact match, never suffix
        return None
    return raw

Trace:

https://good.example/ok              -> allowed
https://trusted.example@evil.example -> rejected (username set; hostname is evil.example)
https://good.example.evil.example    -> rejected (hostname not in set)
//evil.example                       -> rejected (scheme is '')

Failure modes to name

  • startswith("https") accepts https://evil.example and https://good.example.evil.example.
  • Percent-decoding once and then substring-matching misses %252F%252Fevil.example, which decodes twice to //evil.example.
  • A trusted host that itself has an open redirect chains: your exact-match allowlist passes, and the trusted host forwards to the attacker.
  • Scheme-relative //evil.example in a Location header built by string concatenation.

Detection: fuzz the redirect parameter with the four strings above plus a double-encoded variant, and assert on the Location header's host, not on the input string.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How do you integrate asynchronous malware scanning and URL reputation checks without introducing high write latency during URL shortening?

Answer

To keep write latency low (p99 < 50 ms) while preventing malicious actors from using the shortener to bypass reputation filters, you decouple URL creation from safety verification using an asynchronous scanning pipeline paired with a quarantine state machine.

Ingestion and Asynchronous Pipeline

Synchronous calls to third-party reputation feeds (like Google Safe Browsing APIs) introduce external network hops, strict rate limits, and p99 latencies exceeding 200–500 ms. Doing that inline blocks link creation. Instead, process writes through a durable queue:

POST /v1/links (Long URL)
    │
    ├──> 1. Fast Path: Local checks (RFC 3986 parse, domain allow/deny bloom filter)
    ├──> 2. Insert DB (status = 'quarantined' or 'pending', link_key = 'xyz89')
    ├──> 3. Enqueue verification event to Kafka/SQS
    └──> 4. Return HTTP 201 with short URL (p99 < 30 ms)

Worker (Async Consumer)
    │
    ├──> Dequeue event & evaluate against local domain hash-prefix cache
    ├──> If inconclusive, query Google Safe Browsing Lookup API
    └──> If clean: DB status -> 'active', publish invalidation / cache prime
         If malicious: DB status -> 'blocked', revoke redirect, alert

The Resolution Path Gate

Returning 201 Created immediately creates a brief window where a user can navigate to the newly minted link before scanning completes. You handle this on the read path via conditional interstitials:

Link StatusGET /{key} BehaviorResponse Headers / Body
active302 / 307 Redirect directly to targetLocation: https://target.example/path
quarantined (scan pending)200 OK with preview interstitialHTML warning: "Destination link is being verified..." (meta refresh 2s)
blocked (flagged malicious)403 Forbidden or 410 GoneWarning interstitial preventing auto-forwarding

For low-trust or unauthenticated accounts, the link starts as quarantined. When a client dereferences a quarantined link within the ~500 ms scanning window, they receive a light interstitial preview page rather than an automatic 301/302. Once the worker verifies the target, the row flips to active, and subsequent reads bypass the interstitial entirely.

Caching and Invalidation Failure Modes

  1. Stale Cache Vulnerability: If a previously clean domain is compromised or an unvalidated redirect path (OWASP) is later flagged by reputation feeds, a cached 301/302 edge response would bypass the backend block. Set conservative Cache-Control max-age limits (e.g., Cache-Control: private, max-age=300) on redirects, and emit Redis cache eviction events whenever a URL is transitioned to blocked.
  2. Safe Browsing API Quota Exhaustion: Google Safe Browsing enforces strict queries-per-minute quotas. Workers must maintain a local 4-byte hash-prefix database locally (via the Safe Browsing Update API) and only perform full-hash network lookups when local prefix matches occur, preventing worker backlog and queue lag under traffic bursts.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

A short link's destination turns malicious a week after creation. Where does the reputation check belong in the redirect path, and how do you keep it off the hot path?

Answer

Assume the write path already scans at creation. The question is day 8, when the destination starts serving a phishing kit and the short link is already in a million inboxes.

The check belongs after the key lookup and before the 302 is written, and it has to be a local read, not a network call. Resolve key to destination, hash the normalized destination, read a verdict, then emit the redirect. A per-redirect call to Safe Browsing's Lookup API is off by orders of magnitude: the free quota is on the order of 10^4 requests/day, and a shortener at 100k redirects/s would exhaust a year of it in a second. Safe Browsing's other model is the one that fits: the Update API hands you hash prefixes on a schedule, you store them and match locally.

Where the check can sit.

positionadded p99catchesmisses
before key lookupfull scan on 404s toonothing extraburns budget on misses
after lookup, before 302one Redis GET, ~0.3 msdestination verdict, key-level blockverdicts not yet refreshed
edge worker / CDN~0 ms at origincached verdictscold keys, purge lag
write time only0known-bad at creationday-8 rot, this whole question

A trace at 100k rps. GET /aB3xK hits the edge, misses, reaches origin. Origin does Redis GET key:aB3xK (0.4 ms) to get the destination, computes sha256(punycode(host) + path) and does Redis GET verdict:<prefix> (0.3 ms). Hit, value "malware", so the handler returns 403 with a warning body instead of a Location header. Total added cost is under a millisecond and one extra round trip on a connection already open. The verdict key is the destination, not the short key, so one verdict covers every link pointing there: otherwise an attacker mints 10k fresh keys to the same host and every one is a cache miss.

Normalize before hashing. Hash the punycode form of the host, not the raw string, or an attacker rotates Unicode look-alikes of the same registrable domain and each variant is a fresh miss.

The failure that bites is the CDN. If the 302 is cached with max-age=300, blocking the destination does nothing at the edge until those entries expire: you have blocked it in origin and are still redirecting from 40 PoPs. Either keep the redirect max-age short (60s) or purge by key on block. RFC 5861's stale-if-error is the wrong tool here: it exists to keep serving a stale response when the origin is down, which is exactly the behaviour you do not want when the stale response is a redirect to malware.

Decide fail-open versus fail-closed explicitly. If the verdict store is down, fail-open means malicious links redirect during the outage; fail-closed means every link 503s. The workable middle is fail-open on the general store plus a small in-process deny set of confirmed-bad keys, a few thousand entries refreshed every 60s, so a Redis flush does not unblock known malware. Clean verdicts get a short TTL (an hour) so newly-bad destinations are caught within the hour; bad verdicts are cached long, since they only change on review.

Return 403 with a warning page, or 404 if you do not want to confirm the key exists. Do not 302 to a warning page: the Location header leaks the destination and some clients follow it anyway.

Last, the click log. Recording which user clicked a blocked link is personal data under GDPR; keep the block event, minimize the identifier, and set a retention window rather than keeping it forever.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How do you design the interstitial warning page that a short link serves before forwarding to a destination flagged as suspicious, and what does that page change about the redirect contract and the analytics it records?

Answer

The interstitial is a 200 HTML response, not a redirect. The contract changes from one hop to two: GET /{key} returns the warning page with no Location header, and the destination is only reachable through a second request the user triggers, GET /{key}/proceed?t=<signed token>, which re-checks the verdict server-side and then issues the 302. The destination never leaves the server on the first hop, and the proceed link is a token, not the raw URL, if you render the destination as an href, you have built an open redirect (OWASP: unvalidated redirects and forwards).

Why 200 and not "302 to a warning page": a 302-to-warning still puts the destination in the first Location header, so scanners, link previewers and curl -L follow straight through and the warning is decoration. Serving 200 keeps the decision server-side.

clean linkflagged link
status302200
Locationdestinationabsent
bodyemptyHTML warning
Cache-Controlpublic, max-age=300no-store
analytics eventredirectimpression / proceed / bounce

The caching trap is the one people miss. RFC 9110 allows heuristic caching of a 200 with no explicit freshness, so an interstitial served without Cache-Control: no-store can sit in a browser or CDN and keep warning on a link cleared an hour ago, or keep redirecting one flagged a minute ago. Set no-store on the interstitial and keep the verdict TTL short in Redis (300 s is a reasonable starting point; Redis string TTLs are per-key and cheap to refresh).

$ curl -sI https://sho.rt/abc123 HTTP/2 200 cache-control: no-store content-type: text/html; charset=utf-8

$ curl -sI "https://sho.rt/abc123/proceed?t=eyJ..." HTTP/2 302 location: https://example.com/offer

The proceed handler must not trust the token alone: the verdict can change between impression and click:

python

GET /{key}/proceed?t=...

def proceed(key, t): v = verify_hmac(t, secret) # payload: key, verdict_id, exp if not v or v.key != key or v.exp < now(): return 403 verdict = verdict_cache.get(key) # Redis, TTL 300s if verdict is None or verdict.level == "malware": return 403 # re-check; token is not authority return redirect(dest[key], 302)

Analytics stops being one number. A click is now three events: impression (interstitial served), proceed (user clicked through), bounce (left without proceeding). The proceed rate is your false-positive signal: a legitimate campaign that suddenly shows 20% proceed means the reputation feed is wrong, and that is a support-ticket generator, not a security win. GDPR matters here: the decision plus IP is personal data, so keep aggregate counts and only retain per-user rows with a basis.

Two more failure modes. Bots and previewers never click, so link previews break for every flagged link: either serve the destination to verified crawlers or accept it. And the destination string is attacker-controlled: escape it, never interpolate it into HTML, and render the punycode form so IDN homographs are visible (Unicode Security Considerations). Reserve the interstitial for "suspicious"; a confirmed-malware verdict from Safe Browsing should be a hard 403/451, not a warning the user can click past.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

How do you design URL expiration and cleanup at scale without degrading redirect read latencies or overloading the database?

Answer

To design expiration at scale, decouple user-facing expiration checks from storage reclamation: evaluate expiration lazily on read, use Redis TTLs to align cache evictions, and run a batched, rate-limited background worker for physical database deletion.

Read-Path Expiration (Lazy Evaluation)

Every URL record stores an explicit timestamp: expires_at TIMESTAMPTZ NULL. When serving GET /{slug}:

  1. Check the local cache / Redis. Cache entries carry either a matching Redis TTL (EXAT expires_at) or embed the expires_at timestamp inside the cached JSON/msgpack payload.
  2. If the current time is past expires_at, return 410 Gone (RFC 9110 §15.5.11) immediately without issuing a database deletion or looking up the origin URL. Cache the 410 status with a short TTL (e.g., 60 seconds) to prevent repeated database hits for expired keys.
  3. If missing from cache, query the primary datastore by slug. If now() >= expires_at, return 410, populate the negative cache, and leave physical cleanup to the asynchronous process.

Primary Storage Cleanup (Chunked Asynchronous Deletion)

Running DELETE FROM urls WHERE expires_at < NOW() directly on a multi-million-row PostgreSQL table acquires row locks, generates massive WAL volume, triggers autovacuum lag, and induces read replica replication lag.

Instead, use a chunked cursor pattern operating off a partial index:

SQL
-- Index only active rows with an expiration timestamp
CREATE INDEX idx_urls_expiring ON urls (expires_at) WHERE expires_at IS NOT NULL;

-- Background worker batch delete (running continuously off-peak or throttled)
WITH to_delete AS (
    SELECT slug FROM urls
    WHERE expires_at IS NOT NULL AND expires_at < NOW()
    LIMIT 5000
    FOR UPDATE SKIP LOCKED
)
DELETE FROM urls
WHERE slug IN (SELECT slug FROM to_delete);

Latency and Lifecycle Comparison

StrategyRead Path OverheadDatabase ImpactSpace ReclamationEdge Behavior
Synchronous DELETE on ReadAdds 15–40 ms (DB write + lock contention)Spikes locks on active read pathsImmediate per keyFails if edge read cannot write to primary
Unbounded Cron DELETENone during read; sudden spikes during sweepHigh WAL volume, CPU spikes, autovacuum debtImmediate on sweepInconsistent 404 vs 410 if caches drift
Lazy Eval + Batched Worker<0.1 ms (in-memory epoch comparison)Flat, predictable IOPS (5,000-row chunks with sleep)Smooth, continuousConsistent 410 served from cache & edge

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

How would you review a pull request whose risk is hTTPS and mixed destinations?

Answer

Core answer. The PR adds a redirect whose destination comes from the request. The decision that matters is whether the service will ever emit a Location: pointing at http://. I'd default-deny that: reject the request with 400, or refuse to create the link, rather than redirect. Enforce it where the Location header is built, not only at input validation, so no second code path can bypass it.

HSTS on the short host is a separate control and does not help here. Strict-Transport-Security: max-age=63072000; includeSubDomains forces the browser to use HTTPS for your host; it says nothing about where you send the user next.

What actually leaks. A 302 does not forward your cookies to the destination: cookies are scoped to your domain, and the browser will not send them to app.example. The leak is the destination URL itself: the Location header carries the full path and query in cleartext, and the browser's follow-up request to http://app.example puts that same path and query on the wire for anyone on the path to read. If the query holds a token, an email, or a signed parameter, it is exposed.

short URLLocationOn the wire after the hop
https://s.example/ahttps://app.example/x?t=…TLS end to end
https://s.example/ahttp://app.example/x?t=…path + query in cleartext

Referer is not the leak: with the browser default strict-origin-when-cross-origin, a downgrade to http sends no Referer. The URL is.

The check. Parse, then compare the scheme; do not regex the raw string.

Python
from urllib.parse import urlsplit

def is_allowed(dest: str) -> bool:
    p = urlsplit(dest)
    return p.scheme == "https" and p.netloc != ""

urlsplit("https:evil") gives scheme https, netloc '' → rejected. urlsplit("//evil.com") gives scheme '' → rejected. urlsplit("HTTP://app.example") gives scheme http (lowercased) → rejected. A regex on the raw string misses http://x?next=https://y and https://user@evil.com.

Failure modes to look for in the PR. A config flag like ALLOW_HTTP_DESTINATIONS that defaults to true; a preview endpoint that renders the destination while the create endpoint does not re-check; a test suite with only https cases. Ask for a test that asserts a 400 on http:// and on //evil.com.

Log line: redirect_denied reason=scheme dest_host=app.example short_id=a1b2. Host only, never the query.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

What belongs in a runbook section on rate limits on minting, and what does not?

Answer

A runbook section on minting rate limits is a decision procedure for whoever is on call, not a design document. It belongs there if an operator needs it at 3 a.m. to decide whether to act; it does not belong if it only explains why the limit exists. The test is simple: every line either changes what the operator does, or it is noise that will be stale in a month.

Belongs

  • The limit values, their scope, and the config key that holds them, so the operator can read the live value instead of trusting the page.
  • The signal that says the limit is firing: metric name, alert threshold, dashboard link.
  • The response the customer sees, verbatim, so support can explain it without guessing.
  • The action, the escalation path, and who to page.
  • The escape hatch: how to raise a limit temporarily, and who is allowed to approve it.
  • A known-good baseline, so "normal" is distinguishable from "incident."
  • What the limit does not cover, so nobody over-trusts it.

Does not belong

  • The algorithm choice (token bucket vs sliding window) and the rationale behind it.
  • RFC citations used as justification. RFC 6585 defines 429 and permits Retry-After; that is a spec fact, not an operator instruction. The runbook only needs the response shape support will see.
  • Tuning history ("raised from 20 to 30 in March").
  • Speculative capacity numbers nobody measured.
  • Any value copied out of config that will drift from the source of truth.
ItemRunbook?Why
rate_limit.mint.per_owner = 30/minYes, as a pointerOperator reads live value
mint_429_ratio > 5% for 10mYesThis is the trigger
"Token bucket chosen for burst tolerance"NoDesign doc
Override procedure + approverYesWithout it, operator improvises
"We may need more capacity"NoUnactionable

A section that passes looks like this (config keys illustrative):

MARKDOWN
## Mint rate limits
Limit: 30 creates/min per owner_id, 5/min per IP for anonymous.
Live value: rate_limit.mint.per_owner (config service, not this page).
Alert: mint_429_ratio > 5% over 10m -> #oncall-mint.
Customer sees: 429 with Retry-After: <seconds>.
Baseline: p99 429 ratio 0.3% on a normal day.

Steps:
1. Open the mint dashboard. Split 429s by owner_id and by IP.
2. One owner_id dominating -> likely a looping integration.
   Check their create volume, contact them, offer a temporary bump.
3. Many IPs, low per-IP -> distributed abuse. The per-owner limit
   will not catch this. Escalate to security; consider an edge rule.
4. Temporary bump: raise per_owner via config, requires on-call lead
   approval, revert within 24h.

Not covered: a botnet spread across thousands of IPs. Per-owner
limits do nothing there; that is an edge/WAF problem.

Worked trace. Alert fires: mint_429_ratio = 7% for 12 minutes. Operator opens the dashboard, splits by dimension. 92% of the 429s come from a single owner_id creating ~40/min against a 30/min limit: a customer's retry loop, not an attack. Runbook step 2 applies: contact, offer a bump. Had the split shown 400 distinct IPs each at 4/min, step 3 applies and the per-owner limit is irrelevant. The runbook's whole job is to make that fork explicit before the operator starts guessing.

Failure modes. A runbook that restates the config drifts the first time someone changes the limit in the config service: the page lies. A runbook with no override path forces the operator to either do nothing or edit production config unilaterally. A runbook with no baseline can't tell a customer growing 20% month-over-month from an incident, so every alert becomes a page. Each is detected the same way: the next incident review asks "did the runbook tell you what to do?" and the answer is no.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-14

When would you refuse a design because of capacity of the write path?

Answer

Direct answer. Refuse when the peak write rate, after replication and write amplification, exceeds the sustained capacity of the narrowest component in the write path, and the design has no way to shed, buffer, or scale that component before the next peak. Not "writes are high": a named component, a stated ceiling, and no headroom for a node loss.

State these assumptions first. Average and peak write rate, record size, durability requirement (how many copies, synchronous or not), latency budget, and growth. Without them the capacity question has no answer.

Where the ceiling actually is. The write path is a chain: client → app → WAL → primary → replicas → compaction and index maintenance. Each link has a limit; the smallest one decides.

componentorder-of-magnitude ceilingwhat sets it
single Postgres primary, synchronous_commit=on~5–15k commits/sfsync + group commit on NVMe
single DynamoDB partition1,000 WCUdocumented per-partition limit, 1 KB items
single Kafka partitiontens of MB/sone broker's disk plus replication
LSM node (Cassandra, RocksDB)disk bandwidth ÷ write amplificationcompaction

Worked example. Requirement: 40k inserts/s peak, 1 KB rows, survive one AZ loss, p99 < 25 ms. Design: one Postgres primary, synchronous_commit=on, two synchronous replicas, four secondary indexes.

  • Logical throughput: 40k × 1 KB = 40 MB/s.
  • Index amplification: four indexes → five index writes per row → ~5×.
  • WAL plus autovacuum: ~2×.
  • Disk writes ≈ 40 MB/s × 10 ≈ 400 MB/s, and every commit waits on the slowest of three fsyncs.
  • A single primary group-commits at roughly 5–15k/s on NVMe. 40k/s is 3–8× over.

Refuse. The primary is the ceiling, synchronous replication makes the latency worse, and losing a replica doesn't help because the write rate is the problem, not the copy count. Fixes: partition by key, batch writes, or drop synchronous_commit for this table if the durability requirement allows it.

Failure modes and how you'd see them.

  • Hot partition. One key range takes most writes; the ceiling is per-partition, not per-table. Detect with per-partition write metrics (DynamoDB ConsumedWriteCapacityUtilization, Cassandra per-partition latency). Cost to fix: backfill and dual-write a live table. Weeks.
  • Compaction debt. LSM write amplification outruns compaction; writes stall and read latency spikes. Detect with pending-compaction bytes (RocksDB estimate-pending-compaction-bytes, nodetool compactionstats) and write-stall counters. Cost: throttle writes or add nodes.
  • No backpressure. Producer outruns consumer, the queue grows, then OOM. Detect with consumer lag and queue depth. Cost: dropped writes.
  • Quorum latency. Synchronous replication makes write p99 the slowest replica's fsync. Detect by comparing per-replica fsync latency against write p99.

When not to refuse. If the write path holds at 3× peak with one node down, the capacity objection is noise: the real problem is elsewhere (read path, correctness, cost). Refuse on write capacity only when you can name the component, its ceiling, and the peak that breaks it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What is the smallest experiment that would change your mind about cDN in front of 302?

Answer

The experiment: one key, one edit, one stopwatch.

Hypothesis: with Cache-Control: max-age=60 and no purge, a POP that has already cached the 302 keeps serving the old destination after you change it at origin, and the window is bounded by when that POP filled, not by the TTL you set. If the window is longer than your takedown SLA, the CDN either needs purge-on-write or it does not cache 302s at all.

Procedure, about ten minutes:

  1. Publish /x → 302 Location: https://a.example, Cache-Control: max-age=60.
  2. Fetch it through the CDN from one vantage point to fill a POP.
  3. Fetch it from a second, distant vantage point a few seconds later to fill a second POP.
  4. Change origin to Location: https://b.example.
  5. Poll both POPs every 5 s until they return b. Record the delta.
t (s)actionPOP APOP B
0publish → a; fetch from Amiss, fill (expires 60)—
15fetch from B302 amiss, fill (expires 75)
20edit origin → b302 a302 a
60poll302 b302 a
75poll302 b302 b

From the edit at t=20, POP A serves the old destination for 40 s and POP B for 55 s. The spread is the finding: your worst-case takedown is the slowest POP to expire, not the max-age you wrote. A single-POP test would have reported 40 s and hidden the 55.

The experiment that would change your mind the other way is a hit-rate count, and it is one query over a day of origin logs: requests per key. If 10M daily requests land on 9.2M distinct keys, the ceiling on CDN hit rate is 8% and the CDN is a hop in front of a Redis lookup, not a cache. If 10M requests land on 200k keys, the ceiling is 98% and the CDN is offloading real work.

What flips the decision:

  • Stale window exceeds the takedown SLA and purge is not fast enough → do not cache 302 at the CDN; serve Cache-Control: no-store and take the origin load.
  • Stale window within SLA and hit-rate ceiling above roughly 50% → cache with a short TTL plus purge-on-write.
  • Hit-rate ceiling under 10% → drop the CDN; it adds a hop and a failure domain for nothing.

Failure modes the experiment exposes. Purge propagation is vendor-specific and often seconds to minutes rather than instant: time it with the same stopwatch instead of trusting the dashboard. A Vary: Cookie on a redirect that sets a session cookie silently makes every response uncacheable; read the response headers, not the intent. And a viral spike where every POP misses at once sends the full request rate to origin: that is the Redis storm, and it is a separate experiment: block origin egress and watch Redis under the same load.

The smallest version drops the second POP and the logs. One key, one edit, one curl loop against a single POP tells you whether the stale window is bounded by your TTL or by something you do not control. That number is what the decision turns on.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How does multi-region active-active interact with rollback, and where do people ignore that?

Answer

The 90-second version: in active-active, rollback is a data problem, not a deploy problem. Reverting the binary in every region does not revert the rows those binaries already wrote and replicated. So the design rule is that every release must be rollback-safe against the data the previous release can still read, which in practice means expand/contract migrations and never a destructive schema change in the same release as the code that depends on it.

Assumptions that matter: N and N-1 run concurrently during any rolling deploy; replication is asynchronous with nonzero lag; regions deploy independently (canary region first).

Why active-active makes rollback harder than single-region. In one region, rollback is roughly atomic: stop the new code, the database is one consistent thing. In active-active you have three moving parts that do not roll back together:

  1. The code in each region, which rolls back per region at different times.
  2. The schema, which is applied or replicated per region and is not atomic.
  3. The data already written in the new format, which never rolls back.

The window where N and N-1 coexist is the whole problem. A rolling deploy opens it for minutes; a rollback reopens it and leaves it open until every region is back on N-1. During that window, old code reads new-format data.

Trace: bad deploy, three regions, hypothetical numbers.

  • t=0: deploy v2 to us-east. v2 writes status as an enum int; v1 expects a string.
  • t=0–4min: us-east writes ~12k rows with int status, replicating to eu-west and ap-south (lag p99 ~800ms).
  • t=4min: error rate spikes in eu-west. V1 hits an int where it expects a string and throws on read.
  • t=5min: roll back us-east to v1. us-east error rate drops.
  • t=5min onward: eu-west and ap-south still hold the 12k int-status rows, and v1 in us-east now reads them too and throws. The rollback made it worse, because the bad data outlives the bad code.

The fix is upstream: v2 should have dual-written both formats, or written a format v1 tolerates, so that rollback is a no-op on data.

What actually rolls back with the deploy.

ChangeRolls back with the deploy?Why
Add nullable columnyesold code ignores it
Dual-write new + old columnyesold code reads the old column
Backfill new columnnorows already rewritten
Switch reads to new columnyes, if old is still writtenflip the read path back
Drop old columnnodata gone; old code breaks
Publish event / send emailnothe consumer already acted

Where people ignore it.

  • Treating rollback as "revert the deploy." The data written by the bad version is the thing that persists.
  • Shipping a destructive migration in the same release as the code that uses it. "We'll roll back if it breaks": the column is already dropped and replicated.
  • Ignoring the mixed-version window. With N regions and independent deploys, N and N-1 coexist for the deploy duration; rollback extends that window instead of closing it.
  • Assuming replication lag is zero when reasoning about the rollback boundary. Lag means there is no clean timestamp you can point at and say "before this, old format."
  • Assuming a feature flag is an instant global switch. Flag state propagates with its own lag and per-region caches; flipping it off does not un-write what the flag-on path wrote.

Detection. Alert on read-path deserialization errors per region: they cluster in the regions running N-1. Track "rows written by version X still present" as an explicit rollback blocker, and alert on schema-version mismatch between a row's writer version and the reader's expected version.

The senior framing: rollback safety is a property you design into the migration, not a button you press. Expand/contract, one step per deploy, and never let a release both write a new format and delete the old one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How would you brief product on why analytics privacy delays a ship date?

Answer

The briefing is a decision document, not a compliance lecture. Open with the date and the options, not with article numbers.

"Analytics as specced logs IP and a device ID on every event. Under GDPR that's personal data: Recital 30 names online identifiers, and the CJEU confirmed IPs in Breyer (C-582/14, 2016), so it needs a DPIA before we process it. That's the delay. Here are three ways to ship, and what each costs."

Why the delay is calendar time, not effort. A DPIA (GDPR Art. 35) is a documented process: describe the processing, assess necessity and proportionality, name mitigations, DPO reviews and signs off. Scoped to one analytics pipeline that's 2–3 weeks elapsed, most of it waiting on review, not engineering. If residual risk stays high after mitigation, Art. 36 prior consultation with the supervisory authority is 8 weeks minimum and you don't control the clock. Data minimization is a schema change: drop the identifier from the event, re-instrument the client, accept a discontinuity in the series. Consent gating (ePrivacy Directive 2002/58/EC Art. 5(3) for cookies and local storage) changes the funnel and needs UX plus legal review.

OptionShip dateKeepsLosesCost
Ship without identifieron timeevent counts, funnelper-user attribution, session stitching1 wk re-instrument
Pseudonymize, rotating salt+1 wkattribution within rotation windowcross-window joins, fraud lookbackkey management + DPIA
Consent-gated analytics+2–3 wkfull fidelity for consenterspart of the EU samplebanner UX + legal
Full DPIA first+3 wk, or +8 if Art. 36everythingthe dateDPO time

The arithmetic that lands with product. If opt-in runs 60% (illustrative), a metric measured on 1M daily events now sees 600k. Standard error scales as 1/√n, so a ±1.0% conversion estimate becomes ±1.29%. If the launch gate is "conversion within 0.5% of target," you cannot clear it on the consenting subset alone. That sentence moves a roadmap; "privacy" does not.

Failure modes, and how you'd see them.

  • Briefing as a lecture: product hears "legal says no" and escalates. Detection: you're asked "who's blocking this?" instead of "which option do you recommend?"
  • Promising "we'll add retention later": retention jobs never get prioritized. Detection: the raw table is still there at next quarter's review.
  • Consent banner tanks the metric and privacy takes the blame. Detection: the dashboard shows a step change at banner launch, not at the product change.

The decision criterion is whether the processing is "likely to result in high risk": scale, sensitivity, new technology. Aggregate counts with no identifier: no DPIA, ship on time. Per-user behavioral profiles: the DPIA is the date.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

What would you ask a candidate who recites what to draw first in the interview but cannot apply it?

Answer

Ask for a number, a failure, and a constraint change: in that order. A candidate who has memorised the diagram can name the boxes; these three probes make them operate the boxes.

1. "You drew a cache. What's the key, the TTL, and the hit rate you're assuming?" Recited: "Redis, LRU, it's fast." Applied: the key is the short code, the TTL is 24h for hot links or none for permanent ones, and the hit rate is high because reads are Zipfian. A small set of links takes most of the traffic. The follow-up that finishes it: "What happens on a miss at 10k QPS?" A miss is a point read on the primary key of the store of record, 1-5 ms, and 5% of 10k is 500 QPS of misses, which one Postgres primary absorbs.

2. "Two writers pick the same code in the same millisecond. What happens?" Recited: "ZooKeeper for locks." Applied: a unique index on short_code plus INSERT ... ON CONFLICT DO NOTHING, retry with the next code; or a pre-allocated key range from a counter with a step of 1000, so no two writers ever draw the same code. The lock is an answer to a problem the unique index already solves.

3. "The customer edits the destination of a live link. What breaks?" Recited: "We purge the cache." Applied: a 301 is cached by the browser indefinitely and you cannot purge a browser, so the edit never reaches the user. That is why the default is 302 unless the link is immutable.

Then the arithmetic probe, which no reciter survives:

"At 10k writes/s with 7-character base62 codes, how long until you exhaust the space?" 62^7 = 3.52 × 10^12 codes. At 10^4/s that is 3.52 × 10^8 seconds, about 11 years. So 7 characters is fine at that rate and 6 is not: 62^6 = 5.68 × 10^10, about 66 days. A candidate who has only memorised "use base62" can produce neither number.

probereciterapplier
cache"Redis, LRU"key, TTL, hit rate, miss QPS
uniqueness"ZooKeeper lock"unique index + retry, or key-range allocator
redirect"301, purge it"301 is browser-cached and unpurgeable; 302 by default
capacity"base62"62^7 ≈ 3.5e12, ~11 years at 10k/s

The failure mode is uniform: the reciter answers the question you asked and freezes when you change one constraint. So change one. "Now add custom aliases and an enterprise host allowlist." The counter allocator dies: a custom alias has to be checked against the same namespace, so you need a lookup table with a unique index and a reserved range for generated codes. A candidate who can make that change out loud is applying the design; one who repeats the diagram is not.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How would you document when not to build one so the next owner can operate it?

Answer

A when-not-to-build decision is only useful to the next owner if the record tells them three things: what you rejected, the numbers that made it wrong, and what would have to change for the rejection to stop holding. Write it as a decision record in the same repo as the code, committed in the PR that shipped the simpler thing, so it moves when the code moves. A wiki page drifts; a file next to the handler gets reviewed.

State the assumptions first: expected create rate, read rate, destination trust, and who owns the service. Then answer.

The record

MARKDOWN
# ADR-014: link shortener — Postgres table, not a platform

Status: accepted 2025-03-11
Decided by: @you          Revisit owner: @platform-oncall

## Decision
One table `links(key text primary key, url text, owner text, created_at timestamptz)`
plus a 302 handler. No custom KV, no abuse scanner, no CDN.

## Rejected
Partitioned KV store + async abuse scanner + edge cache.

## Why rejected (measured 2025-03-10)
- creates: 200/week ≈ 3.3e-4/s. Peak observed: 12 in one hour.
- redirects: 40 rps average, 180 rps peak, p99 12 ms.
- destinations: corporate allowlist, ~30 hosts, all owned by us.

## Tripwires — revisit if any fires
| signal | threshold | measured by | action |
| --- | --- | --- | --- |
| creates | >50/s for 10 min | delta of pg_stat_user_tables.n_tup_ins | re-open ADR |
| redirect p99 | >80 ms | app latency histogram | add cache |
| non-allowlist destination | any | insert trigger | add scanner |

Why the rejected design was wrong, not just bigger

A partitioned KV exists to spread write load once a single primary's write path saturates. At 3.3e-4 writes/s the primary is idle; the partition buys throughput you are five orders of magnitude away from needing. The abuse scanner exists because a public shortener accepts arbitrary destinations, so the threat is a stranger pointing a trusted-looking link at malware. With an allowlist the destination set is finite and reviewed, so the scanner has nothing to classify. The CDN exists to absorb redirect fan-out across geographies; 180 rps peak is one box. Each rejected piece maps to a condition you do not have: that mapping is the part the next owner needs.

Failure modes of the documentation itself

  • Record names the rejected option but has no tripwire. The next owner inherits an unarguable constraint and either obeys it forever or rips it out blind. Detect it by grepping the ADRs for a "revisit if" section; if it is missing, the record is a slogan.
  • Numbers with no date and no measurement method. "200/week" from a launch-week spike is not a rate. Date every figure and name the query that produced it.
  • Tripwire with no owner. Nobody watches it. Name the person or the rotation, as in the header above.
  • Handover doc that describes only the current design. The next owner cannot tell which parts are load-bearing. The rejected section is what tells them what they are allowed to change.

At handover

Walk the next owner through the tripwire table and the query behind each row, so they can reproduce the numbers themselves. If a tripwire has already fired, the ADR is stale: re-open it rather than patching around it.

Curated: · Written: · Reviewed:

Difficulty: Medium