All modules

Distributed patterns and operations: interview questions

16 questions. Try answering out loud before you open the model answer.

1. Which rate limiting algorithm would you use for a public API, and where would you enforce it?

Mid-levelrate-limitingapi-gateway

What the interviewer is really testing

Whether you can choose an algorithm from the requirements (burst tolerance, memory, accuracy) instead of reciting all five, and whether you know that limits belong at more than one layer.

Show the model answer, follow-ups and checklist

Model answer

I would start from what the limit is for. On a public API the goals are usually to stop one customer hurting the others and to give customers a quota they can reason about. Honest clients are bursty: one page load can fire ten calls at once. So I want an algorithm that tolerates short bursts and enforces an average.

That points to a token bucket per API key, for example refilling at 100 tokens per second with a capacity of 200. It needs two numbers per key, it is cheap to evaluate, and its two parameters are exactly what I would publish in the documentation. Expensive endpoints can cost more than one token.

I would not use a fixed window for the main limit, because a client can spend two quotas back to back across a window boundary. For small, strict limits, such as five login attempts per fifteen minutes per account, I would use a sliding window log, which is exact and cheap at that size. If a downstream needed a constant rate, I would queue in front of it (a leaky bucket) instead of rejecting.

Where to enforce it:

  • At the API gateway for the per-key limit, so that rejection happens before any service does work.
  • At the edge, a coarser per-IP limit for unauthenticated traffic.
  • In the service, limits that depend on business meaning, such as exports per day on a given plan.

What the client sees: 429 with a Retry-After header, plus remaining-quota headers so that well-behaved clients can pace themselves.

With more than one gateway node, the counters go in Redis and each check is a single atomic operation. I would fail open if Redis is unreachable, because a short period without limits is better than rejecting all traffic, and I would say so explicitly as a trade-off.

Likely follow-ups

Why not simply limit by IP address?
Many users share one address behind a corporate NAT or a mobile carrier, so an IP limit punishes the innocent, and an attacker can rotate addresses. Use an IP limit only for unauthenticated traffic, as a coarse first filter. For authenticated traffic an API key or user id is the fair unit.
How would you pick the actual numbers for rate and burst?
From capacity and observed usage. Measure what the backend can sustain, look at the high percentiles of legitimate per-customer traffic, and set the limit above normal use but low enough that a few misbehaving customers cannot consume the headroom. Run the limiter in log-only mode first to see who would have been blocked.
What is the difference between rate limiting and load shedding?
Rate limiting enforces a policy per caller, whether or not the system is busy, and answers with 429. Load shedding protects the server when total demand exceeds capacity, based on signals such as queue depth or concurrency, and answers with 503 whoever is calling. A public API needs both.
A customer says they are being limited while under their quota. How do you investigate?
Find out which limit rejected them, which is why responses and logs should name the policy and the key. Common causes are several of their services sharing one key, their own retries counting against the quota, a per-IP limit at the edge catching an office behind one address, or a burst that exceeds the bucket size even though the average is fine.

Common mistakes

  • Listing all five algorithms without choosing one or tying the choice to a requirement.
  • Proposing a fixed window and not mentioning that it allows twice the limit across a boundary.
  • Enforcing only by IP address.
  • Never saying what the client receives: the status code and how long to wait.
  • Keeping counters in each gateway's memory without noticing that this multiplies the limit by the number of gateways.

A strong answer includes

  • Starts from the purpose of the limit and the shape of legitimate traffic
  • Chooses token bucket for the main limit and states a rate and a burst size
  • Explains why a fixed window was rejected
  • Uses a different algorithm where the need differs, such as an exact log for login attempts
  • Places per-key limits at the gateway and business limits in the service
  • Returns 429 with Retry-After
  • Mentions shared, atomically updated counters and a fail-open or fail-closed decision

Revise: Rate limiting algorithms

2. You have 60 gateway nodes across three regions. How do you enforce one rate limit per customer across all of them?

Staffrate-limitingdistributed-countersredis

What the interviewer is really testing

Whether you see the tension between accuracy, latency and availability in a shared counter, and can choose a point on that line instead of insisting on an exact global count.

Show the model answer, follow-ups and checklist

Model answer

The two naive options sit at opposite ends. Counting in each node’s memory costs nothing per request and lets a customer have up to 60 times the limit. Checking one central counter on every request is exact, and puts a network round trip and a single dependency in front of all traffic. The design is a choice of where to sit between them.

Within a region I would use a shared Redis cluster and make each check one atomic operation: a Lua script that refills and decrements a token bucket, or a single INCR on a window counter. Inside a region the round trip is usually around a millisecond, which most APIs can afford.

To cut round trips for busy customers, each gateway can hold a small local allowance. It takes a batch of tokens from Redis, say 50, serves from memory, and returns for more when they run out. The limit becomes approximate. The worst overshoot is about the batch size times the number of nodes, and I control that by tuning the batch.

Across regions I would not synchronise per request, since cross-region latency is tens of milliseconds or more. I would give each region a share of the customer’s limit, sized by where that customer’s traffic goes and adjusted periodically. The alternative is regional counters replicated asynchronously, accepting a few seconds of overshoot. Most customers send most of their traffic to one region, so the split is rarely felt.

Failure. The Redis call gets a short timeout, so that a slow Redis cannot slow every request. If Redis is unreachable, gateways fall back to an in-memory limit of roughly the regional limit divided by the node count. That is neither fully open nor fully closed.

I would state the principle out loud: this limiter is approximate by design. Overshooting by a few percent for a few seconds is fine. Adding 50 ms to every request, or taking the API down when the counter store fails, is not.

Likely follow-ups

Why must the check be atomic, and how do you get that in Redis?
If a node reads the count, compares it and then writes, two nodes can both read 99 and both allow the hundredth request. Use a single INCR and compare the value it returns, or a Lua script, which Redis runs without interleaving other commands. Set the expiry inside the same script, or a crash between the two commands leaves a counter that never expires.
One customer produces 30% of all traffic, so its counter is a hot key. What do you do?
A single key lives on one Redis shard, so adding shards does not help. Local batching does: if each gateway takes 100 tokens at a time, the key sees one hundredth of the operations. For the very largest customers you can also give each gateway group its own sub-bucket that adds up to the customer's limit.
Could you avoid shared state by routing each customer to one gateway node?
Yes, with consistent hashing on the customer key at the load balancer, each node can count locally and be exact. The costs are uneven load when customers differ greatly in size, counters that reset or move when nodes change, and a load balancer that must parse the key. It works well for a modest number of nodes and is sometimes combined with a shared store.
The gateways' clocks differ by a few hundred milliseconds. Does that matter?
It can for a token bucket, because refill is computed from elapsed time, and nodes that disagree about the time will refill inconsistently. Take the time from one source, such as the Redis server inside the script. Coarse window counters are less sensitive, since a small skew only blurs the window edge.

Common mistakes

  • Insisting on an exact global count and paying a cross-region round trip on every request.
  • Reading and then writing the counter as two steps.
  • Having no plan for the counter store being slow or unreachable.
  • Forgetting that purely local counters multiply the limit by the number of nodes.
  • Assuming that adding Redis shards fixes a single hot key.

A strong answer includes

  • Names the two extremes (local counters, one central counter) and what each costs
  • Uses a shared store within a region with an atomic check-and-update
  • Reduces round trips with local token batches and states the bound on overshoot
  • Avoids synchronous cross-region calls, using regional shares or asynchronous replication
  • Sets a short timeout on the counter call and defines the fallback when it fails
  • Says plainly that the limit is approximate and why that is acceptable

Revise: Rate limiting algorithms

3. We need 64-bit ids that sort roughly by time and can be generated on hundreds of servers. How would you design that?

Seniorunique-idssnowflake

What the interviewer is really testing

Whether you can turn requirements into a bit budget, do the capacity arithmetic aloud, and name the two things that can break uniqueness: clocks and machine ids.

Show the model answer, follow-ups and checklist

Model answer

Those three requirements rule out the simple options. Auto-increment needs one database to issue every id. A UUID is 128 bits. Leased ranges from a ticket server fit in 64 bits, but they sort by block and not by time. So I would use a Snowflake-style id, generated locally in each process.

From the high bits down: one unused sign bit, 41 bits of milliseconds since a custom epoch, 10 bits of machine id and 12 bits of sequence. I would check that budget against the requirement before committing to it:

  • 41 bits of milliseconds is about 69 years from the epoch I choose.
  • 10 bits is 1,024 generators, which covers “hundreds” with room to grow.
  • 12 bits is 4,096 ids per millisecond per generator, about 4 million per second. That is far more than one server needs, so if we expected thousands of pods I would move two bits from the sequence to the machine id.

Generating an id needs no network call. Read the clock. If it is the same millisecond as the last id, increment the sequence, and if the sequence is exhausted, wait for the next millisecond. Otherwise reset the sequence to zero.

Uniqueness then depends on two things, and I would spend my time on those:

  1. Machine ids must be unique among live generators. Each process leases one at start-up from etcd or a database table, with an expiry so that ids are reclaimed, or takes it from a StatefulSet ordinal.
  2. The local clock must never repeat. The generator remembers the last timestamp it used and refuses to issue ids while the clock reads earlier than that.

On ordering, I would be precise: ids sort by creation time to within the clock skew between machines, which is typically milliseconds. That is good enough for pagination and index locality. It is not a strict global order, and if someone needs one, that is a different and more expensive requirement.

Last, I would return ids as strings in JSON, because JavaScript cannot represent every 64-bit integer exactly.

Likely follow-ups

Why use a custom epoch instead of 1970?
Forty-one bits of milliseconds cover about 69.7 years. Counted from 1970 that runs out in 2039. Counted from the service's launch date, the full 69 years are still ahead.
What if you need more than 1,024 generators?
Rebalance the bits. Twelve bits of machine id and ten of sequence give 4,096 generators at 1,024 ids per millisecond each, which is still about a million per second per generator. Or stop giving every process an id: run a small pool of id servers and let application servers fetch ids from them in batches.
Would you ship this as a library or run it as a separate service?
A library has no network hop, but every process needs its own machine id, and with thousands of short-lived pods that id space churns quickly. A service keeps a few generators with stable ids and adds a call, which can be batched, and a dependency. Twitter ran Snowflake as a service. I would choose by how many processes need ids and how often they restart.
Are these ids safe to expose in URLs?
They are unique but not secret. Anyone can read the creation time from the high bits, and ids near a known one are easy to guess. That is acceptable if every request is authorised properly. If the identifier itself must be unguessable, expose a separate random token.
Why not UUID v7?
It gives the same time ordering with no machine ids and no clock checks, and I would prefer it if the 64-bit requirement were soft. It is 128 bits, so it does not fit a BIGINT column, and it doubles the size of every index and foreign key that carries it.

Common mistakes

  • Proposing UUIDs when the question says 64 bits.
  • Reciting 41, 10 and 12 bits without checking them against the stated scale.
  • Saying nothing about how machine ids are assigned or what happens when two generators share one.
  • Claiming the ids give a strict global order.
  • Ignoring what happens when the sequence runs out within one millisecond.

A strong answer includes

  • Explains why auto-increment, UUIDs and plain ticket ranges do not meet all three requirements
  • Gives the bit layout with the timestamp in the high bits
  • Does the arithmetic: about 69 years, 1,024 generators, 4,096 ids per millisecond each
  • Adjusts the split to the scale in the question
  • Describes how machine ids are leased and kept unique
  • Handles the clock going backwards and sequence overflow
  • States that ordering is approximate, to within clock skew

Revise: Unique ID generation and Snowflake

4. The clock on one of your Snowflake id generators jumps back by 200 ms. What happens, and how do you defend against it?

Seniorunique-idsclockssnowflake

What the interviewer is really testing

Whether you understand that timestamp-based ids depend on a local clock that never repeats, can tell skew between machines apart from one clock stepping backwards, and can design a defence that fails safely.

Show the model answer, follow-ups and checklist

Model answer

First, the risk. An id is unique because the combination of timestamp, machine id and sequence never repeats. The machine id is fixed, so on a single machine uniqueness depends on the timestamp never going back. If the clock steps back 200 ms and the generator carries on, then for the next 200 ms it is using timestamps it has already used, with the sequence starting from zero in each millisecond just as before. Any id it issued the first time round can be issued again.

It is worth saying what is not a problem: skew between machines. If machine A runs 200 ms behind machine B, their ids cannot collide, because the machine ids differ. Only the ordering is off.

I would defend in layers:

  1. Track the last timestamp issued. If the clock reads earlier than that, do not issue. For a small step, sleep until the clock has passed it. For a large one, return errors, fail the health check so that the load balancer takes this generator out, and raise an alert. With several generators, losing one for a moment is invisible to callers.
  2. Cover restarts. The in-memory record is lost when the process restarts. Either persist the last timestamp every few seconds and wait at start-up until the clock has passed it with a margin, or take a new machine id on every start, which makes the old timestamps harmless.
  3. Reduce the cause. Configure time synchronisation to slew the clock gradually in preference to stepping it, alert on offset, and avoid restoring virtual machines from snapshots.

There is an alternative: when the clock is behind, keep using the last timestamp and keep incrementing the sequence, in effect borrowing from the future. It stays available, but ids drift away from real time, and it only copes with small steps.

I would choose to wait or refuse. One generator being unavailable for 200 ms is a small problem. Two orders with the same id is a very large one.

Likely follow-ups

Why not just use the operating system's monotonic clock?
A monotonic clock never goes backwards, but it counts from an arbitrary point, usually boot, so its values mean nothing across restarts or machines. You can anchor it: read the wall clock once at start-up and add monotonic elapsed time. That protects a running process, but the generator slowly drifts from real time, and the restart case is still open.
How do leap seconds fit into this?
A leap second handled by repeating or stepping the clock is the same hazard as an NTP step, and the same guard covers it. Several large providers, including Google and AWS, smear the extra second gradually over many hours so that the clock never steps.
If duplicates did get out, how would you find out?
Within one table or shard, a primary key constraint rejects the second insert, which shows up as errors. Across shards or services nothing checks, so two entities can share an id silently. That asymmetry is why the generator must prevent duplicates and expose a metric and an alert for every backwards step it sees.
A generator is refusing requests because its clock is far behind. What do callers do?
They retry against another generator, which is why there should be several behind a load balancer or a client-side list. The refusing node fails its health check so that it stops receiving traffic until its clock has passed its last issued timestamp.

Common mistakes

  • Confusing skew between machines, which is harmless for uniqueness, with one machine's clock going backwards.
  • Offering "run NTP" as the whole answer, when NTP corrections are one cause of backward steps.
  • Letting the generator carry on and hoping the sequence number avoids collisions.
  • Forgetting that a restart wipes the in-memory record of the last timestamp.
  • Choosing availability over uniqueness without saying so.

A strong answer includes

  • Explains why a repeated timestamp on one machine can produce duplicate ids
  • States that skew between machines affects only ordering
  • Tracks the last issued timestamp and waits or refuses when the clock is behind it
  • Covers the restart case with a persisted timestamp, a start-up delay or a fresh machine id
  • Reduces the cause: slewing time synchronisation and drift alerts
  • Chooses brief unavailability of one generator over any risk of a duplicate

Revise: Unique ID generation and Snowflake

5. Is a Redis lock enough to stop two workers processing the same order at the same time?

Seniordistributed-locksredisfencing

What the interviewer is really testing

Whether you know that a distributed lock is a lease that can be lost without the holder noticing, and can separate uses where that only wastes work from uses where it corrupts data.

Show the model answer, follow-ups and checklist

Model answer

It depends on what happens when the lock fails, because it can fail.

The mechanism itself is fine: SET lock:order:42 <random> NX PX 30000 to acquire, and a script that deletes the key only if the value still matches to release. That gives mutual exclusion nearly all the time. It breaks in two ways.

  1. The holder outlives its lease. A garbage collection pause, a stalled virtual machine or a slow network call can last longer than 30 seconds. Redis expires the key, a second worker acquires the lock, and the first resumes with no idea that anything changed. Both are now in the critical section. A longer expiry makes this rarer, not impossible.
  2. Redis fails over. Replication is asynchronous, so a promoted replica may not have the key and will grant the lock again.

So I would ask what “processing the order” does. If an overlap only wastes work, for example two workers rendering the same invoice PDF, a Redis lock is the right tool: cheap and good enough. If an overlap charges a card twice or decrements stock twice, the lock cannot be the safety mechanism. I would put the guarantee at the resource instead:

  • A conditional update: UPDATE orders SET status = 'processing' WHERE id = 42 AND status = 'pending'. Only one worker’s update changes a row, and the other stops.
  • An idempotency key on the payment call, derived from the order id, so that a second attempt is recognised and ignored.
  • If I must keep lock semantics, a fencing token: a number that increases with each grant, which the database checks on every write. A consensus-backed store such as etcd or ZooKeeper provides one naturally.

I would still keep the Redis lock in front as an optimisation, since it prevents most duplicate work, and rely on the conditional write for correctness. The lock makes the collision rare, and the resource makes it harmless.

Likely follow-ups

What is a fencing token, and why does the resource have to check it?
It is a number that the lock service increases on every grant. The holder sends it with each write, and the resource rejects any write with a token lower than the highest it has seen. The check has to be at the resource because a paused holder cannot know its lease has expired, so nothing on the holder's side can be trusted to stop it.
Would a background thread that keeps renewing the lease fix the pause problem?
It helps with work that simply takes longer than the expiry. It does not help when the whole process is paused, because the renewal thread is paused too. It also has a failure of its own: if the worker thread hangs while the renewal thread stays healthy, the lock is held for ever by a worker that is doing nothing.
Does Redlock make it safe?
Redlock takes the lock on a majority of five independent Redis nodes, which covers the failover case. It does not stop a holder that pauses after acquiring, and it does not issue a fencing token. Kleppmann argued on those grounds that it should not guard correctness. Sanfilippo replied that its timing assumptions are reasonable and that pauses affect every lease-based lock. Either way, my design would not rest correctness on it.
How would you choose the expiry time?
Much longer than the slow tail of the critical section, measured and not guessed, and shorter than the stall you can tolerate after a holder crashes. If the work varies a lot in length, use a moderate expiry with renewal. Then accept that whatever value you choose can still be exceeded.
What if all the data is in one PostgreSQL database?
Then I would not use Redis at all. A row lock with SELECT FOR UPDATE, or SKIP LOCKED for a job queue, is held by the transaction and released when it commits, aborts or loses its connection. The lock and the data are in the same system, so there is no window in which one says yes and the other disagrees.

Common mistakes

  • Answering "yes, SET NX is atomic" and stopping there.
  • Releasing with a plain DEL, which can delete a lock that now belongs to another worker.
  • Believing that a longer expiry or a renewal thread removes the problem instead of making it rarer.
  • Saying Redlock makes the lock safe for correctness without mentioning pauses or fencing.
  • Using a lock where a conditional write or a unique constraint would do the job.

A strong answer includes

  • Gives the correct acquire and release: SET with NX and PX, a random value, compare-and-delete
  • Explains how a pause can make the holder outlive its lease
  • Mentions that asynchronous replication can lose the lock on failover
  • Asks whether an overlap wastes work or corrupts data, and answers differently for each
  • Puts the correctness guarantee at the resource: conditional write, idempotency key or fencing token
  • Keeps the lock, if at all, as an optimisation

Revise: Distributed locks

6. Two nodes in your cluster both believe they are the leader. How did that happen, and how do you make it harmless?

Staffleader-electionsplit-brainfencing

What the interviewer is really testing

Whether you understand that election gives one leader per term and not one believer at every instant, and that safety comes from fencing at the receivers, not from better failure detection.

Show the model answer, follow-ups and checklist

Model answer

There are two ways to end up here, and they have different fixes.

No quorum. If the nodes decide leadership by watching each other, as a primary and a standby with heartbeats do, a network fault between them makes each conclude that the other is dead, and both act as leader until it heals. The fix is structural. Leadership has to be granted by a majority, through a consensus protocol or a store such as etcd or ZooKeeper, so that at most one side of a partition can elect.

Stale belief. Even with a quorum, the old leader may not know that it has been replaced. Leadership is a lease. If the old leader is frozen by a long pause, cut off from the store, or running a slow timer, the lease expires on the store’s side and a new leader is elected in a higher term. The old one carries on until it notices. Timing cannot close that window completely, because a pause can fall after any check the leader makes.

So I would make the overlap harmless:

  • Each election produces a term, or epoch, that only goes up, and the leader stamps every request with it.
  • Every receiver remembers the highest term it has seen and rejects anything older. The stale leader’s first write after the change is refused, which also tells it to step down.
  • If the leader’s writes go through a replicated log, as in Raft, a stale leader cannot commit, because it cannot get a majority to acknowledge.
  • Side effects outside the system, such as emails and payments, cannot be fenced, so they carry idempotency keys.

I would also narrow the window: the leader times its lease with a monotonic clock and stops acting if it has not renewed within a deadline shorter than the lease.

When diagnosing, I would read the terms in the logs. Two leaders in the same term means the election is broken. Two leaders in different terms overlapping for a few seconds is expected, and the question becomes whether every receiver checked the term.

Likely follow-ups

What is STONITH, and where does it fit?
It stands for "shoot the other node in the head". Before a new leader takes over, it forcibly powers off or isolates the old one through an out-of-band channel, such as a management controller or a cloud API. Classic high-availability clusters such as Pacemaker rely on it. It removes the stale leader instead of rejecting its writes, and it only works while that out-of-band channel is reachable.
Can a deposed Raft leader still serve reads?
Yes, if it answers from its local state without checking. It cannot commit writes, but it can return data that is out of date. The fixes are to confirm leadership with a majority before answering each read, which is what etcd does for linearizable reads, or to rely on a leader lease, which is faster and brings back a dependence on bounded clock drift.
How long should the leader lease be?
Long enough to ride out ordinary pauses and network stalls, and short enough that failover meets the recovery target. A few seconds to a few tens of seconds is typical. Shortening it speeds up failover and increases needless elections, each of which is a short outage of the leader's work.
Both primaries accepted writes for 40 seconds before anyone noticed. What now?
Choose one history as the truth, normally the side that held the quorum. The other side's writes must be extracted from its log and either replayed, reconciled by hand or discarded, and some will conflict with writes on the surviving side. It is slow and manual, which is the practical argument for preventing the overlap with quorum and fencing.

Common mistakes

  • Answering "use Raft" or "use ZooKeeper" without explaining how a stale leader is actually stopped.
  • Trying to fix split brain with shorter timeouts or more heartbeats.
  • Assuming a leader always knows when it has lost leadership.
  • Forgetting side effects outside the system, such as emails and payments, which cannot be fenced.
  • Running an even number of voters, or two nodes with no tie-breaker.

A strong answer includes

  • Distinguishes election without a quorum from a stale leader under a quorum-based election
  • Requires a majority, through consensus or a consensus-backed store, so one side of a partition can elect
  • Explains why a lease cannot fully prevent a paused or slow leader from acting
  • Stamps every leader request with a term or epoch that receivers check
  • Notes that a log-based leader cannot commit without a majority
  • Uses idempotency for external side effects
  • Reads term numbers in logs to tell a broken election from an expected, fenced overlap

Revise: Leader election

7. How do your services find each other? Would you use client-side or server-side discovery?

Mid-levelservice-discoveryload-balancingkubernetes

What the interviewer is really testing

Whether you understand the moving parts behind a service name (registry, health checks, who picks the instance) and can justify a choice by team and traffic instead of by fashion.

Show the model answer, follow-ups and checklist

Model answer

Instances come and go with autoscaling and deploys, so addresses cannot be configured by hand. Something has to keep a live list of instances per service, which is the registry, fed by registration and health checks. The real question is who reads that list and picks an instance.

Server-side discovery. The caller uses one stable name. Behind it, a load balancer or proxy tracks the healthy instances and forwards the request. Callers need nothing special and can be written in any language. The cost is usually an extra hop, and a load balancer that must itself be scaled and kept available.

Client-side discovery. The caller fetches the instance list from the registry, caches it and balances for itself. There is no extra hop, and balancing can be smarter: prefer the same zone, pick the instance with the fewest requests outstanding. The cost is discovery and balancing logic in every service, in every language, all kept in step.

My default for a typical product company on Kubernetes is server-side discovery through Kubernetes Services. The platform registers pods automatically, readiness probes remove unhealthy ones, callers use a DNS name that maps to a stable virtual IP, and kube-proxy forwards on the caller’s own node, so there is no separate load balancer hop. It is the least to build and operate.

I would move towards client-side behaviour only when I hit a limit. The usual one is gRPC or HTTP/2: a Service balances per connection, so a long-lived connection pins a caller to one pod. Then I would use a headless Service with gRPC’s own balancing, or a service mesh sidecar, which gives client-side discovery with no library in the application, at the cost of running the mesh.

Traffic from outside the cluster is always server-side: a public load balancer or an API gateway.

Whichever I choose, the list is a little out of date, so callers need timeouts and a retry on a different instance.

Likely follow-ups

Why not just use DNS with a low TTL?
DNS answers are cached at several layers, some clients do not honour the TTL, and a caller with pooled connections never looks the name up again. A very low TTL also multiplies the load on the DNS servers. DNS is fine for the stable address of a load balancer and a poor way to track individual instances.
What should a health check actually test?
Whether this instance can serve: the process is up, has finished warming, and its own resources are fine. It should not fail because a shared dependency is slow, or every instance fails together and the service vanishes. In Kubernetes, readiness decides whether a pod receives traffic and liveness decides whether it is restarted, and mixing them up causes restart storms.
How does an instance leave without dropping requests?
It deregisters, or starts failing readiness, while it is still serving. It waits a few seconds for load balancers and callers to learn of the change, finishes the requests in flight, and then exits. In Kubernetes the termination signal and the removal from endpoints happen in parallel, so the application or a preStop hook has to add that wait.
What does a service mesh add on top of Kubernetes Services?
Per-request load balancing that understands HTTP/2 and gRPC, plus retries, timeouts, mutual TLS and uniform metrics, all applied by a proxy beside each pod and configured centrally. The price is extra latency per call, resources for every proxy, and a control plane to run and upgrade.

Common mistakes

  • Saying "DNS" or "Kubernetes handles it" with no account of what happens underneath.
  • Hard-coding addresses, or a static host list, in configuration.
  • Claiming client-side discovery is simply faster, without the cost of a library in every service.
  • Ignoring that the instance list is always slightly stale.
  • Proposing gRPC over Kubernetes Services without noticing that balancing is per connection.

A strong answer includes

  • Explains why static addresses fail with autoscaling and deploys
  • Names the registry and how instances are registered and health-checked
  • Compares client-side and server-side on the extra hop, client complexity and balancing quality
  • Makes a choice and ties it to the platform, languages and team size
  • Uses server-side discovery for traffic from outside
  • Mentions per-connection balancing with gRPC or HTTP/2 and a fix
  • Plans for stale entries with timeouts and retries on another instance

Revise: Service discovery

8. An instance was terminated 30 seconds ago and callers are still sending it requests. Why, and how do you fix it?

Seniorservice-discoveryhealth-checksfailure-modes

What the interviewer is really testing

Whether you can trace how a membership change travels through every cache between the registry and the caller, and design for that staleness instead of expecting it to be zero.

Show the model answer, follow-ups and checklist

Model answer

Discovery is a chain of caches, and every link adds delay. I would walk the chain from the instance to the caller.

  1. Detection. If the instance was killed without deregistering, the registry only finds out from missed heartbeats or failed health checks. A check every 10 seconds with removal after three failures is 30 seconds by itself.
  2. Propagation. The change has to reach whatever routes traffic: registry replicas, load balancer configuration, forwarding rules on each node, sidecar proxies.
  3. Caller caches. Clients that poll the registry every 30 seconds, and DNS answers cached for their TTL or longer.
  4. Open connections. Pooled connections to the dead instance stay in the pool until they produce an error. If the host vanished without closing them, requests hang until a timeout instead of failing fast.

The fix has two halves.

Make planned exits clean, since most exits are deploys and scale-in. On shutdown the instance deregisters first, or starts failing its readiness check, keeps serving for a few seconds while the change spreads, finishes the requests in flight, and then exits. Done this way, callers never see a dead address.

Tolerate crashes, because that window cannot be zero:

  • Short connection timeouts and sensible request timeouts.
  • Retry idempotent requests on a different instance.
  • Passive health checking in the caller or proxy: eject an instance after a few consecutive failures without waiting for the registry.
  • Keepalive probes, so that dead peers are found on idle connections.

Only then would I tune detection, with faster checks or a lower failure threshold, and carefully. Checks that are too eager remove healthy instances during a brief pause, and that can cascade when capacity is already tight.

Before changing anything I would confirm which link is responsible. The registry’s logs show when it dropped the instance, the callers’ metrics show when their lists changed, and the error type helps: connection refused suggests a stale list, while timeouts suggest dead connections or a vanished host.

Likely follow-ups

The registry itself goes down for ten minutes. What happens?
If callers keep their last known list, existing traffic carries on, and ordinary retries cover the few entries that go stale. What stops is change: new instances cannot register, so scale-outs and deploys stall. The failure to avoid is callers clearing their list, or the registry expiring every entry because it stopped hearing heartbeats.
Why not check health every second and remove an instance after one failure?
Because false positives become frequent. A short garbage collection pause or one lost packet would remove a healthy instance, and under load, when everything is a little slow, the checks would strip capacity exactly when it is needed. Requiring two or three consecutive failures trades a few seconds of detection time for stability.
Some callers see "connection refused" and others see timeouts. What does each tell you?
Refused means something at that address answered and nothing is listening on the port, so the failure is fast and a retry elsewhere is cheap. A timeout means packets are vanishing, as when the host is gone, and each attempt ties up a connection or a thread until the timeout fires. Timeouts are the damaging case, which is why connection timeouts should be short.
Why can a Kubernetes pod receive requests after it has been sent SIGTERM?
Removing the pod from the Service endpoints and signalling the container happen in parallel, and every node's kube-proxy and every ingress controller applies the change on its own schedule. A pod that exits at once will be sent a few more requests. The usual fix is to keep serving for a few seconds after the signal, with a preStop hook or in the application, inside a long enough grace period.

Common mistakes

  • Blaming only the DNS TTL and ignoring the health check interval and pooled connections.
  • Trying to drive staleness to zero with very aggressive health checks.
  • Having no shutdown sequence of deregister, wait, drain and exit.
  • Retrying on the same instance that just failed.
  • Treating planned terminations and crashes as the same problem.

A strong answer includes

  • Walks the chain: detection, propagation, caller caches, open connections
  • Adds up realistic delays, such as check interval times failure threshold
  • Separates planned exits, which can be made clean, from crashes, which must be tolerated
  • Gives the graceful shutdown order: deregister, wait, drain, exit
  • Adds caller-side defences: short timeouts, retry on another instance, ejecting failing instances
  • Warns that over-aggressive health checks remove healthy instances
  • Uses data to find which link is slow before changing anything

Revise: Service discovery

9. A dependency recovers from a brief outage and is immediately knocked over again by its own callers. What is happening, and how do you stop it?

Seniorresilienceretriesbackoff

What the interviewer is really testing

Whether you see retries as load, can explain both synchronisation and amplification across layers, and can give layered defences on the client and the server instead of only saying "add exponential backoff".

Show the model answer, follow-ups and checklist

Model answer

This is a retry storm. While the dependency was down, every caller’s requests failed and went into retry loops. When it comes back it receives normal traffic, plus retries from every client, plus retries of those retries from each layer above. It also returns in its weakest state, with cold caches and connections to re-establish. So it is overloaded at once, starts timing out, and that produces more retries. The load caused by the failure keeps the failure going.

Two things make it worse. Synchronisation: clients that failed together and use the same backoff schedule retry at the same instants, so load arrives in spikes. Amplification: if the app, the gateway and the service each try three times, one user action becomes up to 27 calls.

I would fix it in layers.

On the client side:

  • Capped exponential backoff with full jitter, so retries spread across the whole window.
  • A small attempt limit, and retries at one layer only. Other layers pass the failure through.
  • A retry budget, for example retries limited to 10% of normal request volume, so a full outage adds a little load and not a multiple.
  • A circuit breaker, so sustained failure stops calls altogether, and respect for Retry-After.

On the server side, because I cannot trust every client:

  • Load shedding: a concurrency limit with early, cheap rejection, so accepted requests still finish within their deadline.
  • Priority for critical traffic, and a gradual ramp of admitted traffic after recovery.

Finally, retried writes must carry idempotency keys, or the storm also produces duplicates.

Likely follow-ups

Why full jitter and not a fixed backoff with a small random offset?
The aim is to spread retries evenly over time, and what protects the server is the aggregate arrival rate. A small offset still leaves most retries clustered around the same instants. Full jitter picks a wait anywhere between zero and the backoff value, so the whole window is used and the peak is lowest.
The callers are mobile apps already installed on phones, so you cannot change their retry logic this week. What can the server side do?
Shed load at the edge. Enforce a concurrency or rate limit at the gateway, reject the excess cheaply with 429 or 503 and a Retry-After header, and prioritise critical endpoints. Then admit traffic gradually as the service warms up, and add capacity temporarily if the backlog is large.
How would you recognise a retry storm from your metrics?
Request rate at the dependency rises while its success rate falls, which is the opposite of an organic traffic increase. Traffic at the edge stays near normal while internal traffic multiplies. A retry counter or an attempt-number header on each call makes the ratio of retries to first attempts directly visible.
How does a retry budget differ from a circuit breaker?
A budget is a continuous cap on the share of traffic that may be retries, so isolated failures are still retried while a broad failure is not amplified. A breaker stops all calls to the dependency once failure is sustained. They complement each other and many systems use both.

Common mistakes

  • Proposing exponential backoff alone, which spaces the waves out but leaves every client retrying at the same instants.
  • Capping attempts per request and assuming that bounds load, when three attempts at each of three layers is 27 calls.
  • Putting all the fixes in clients and none in the server, which cannot rely on every client behaving.
  • Retrying non-idempotent writes during the storm and creating duplicates on top of the outage.
  • Scaling the dependency up as the only response, when the excess load is self-inflicted and grows with capacity problems elsewhere.

A strong answer includes

  • Names it as a retry storm and explains that failure-induced load is keeping the service down
  • Explains synchronisation and fixes it with capped exponential backoff plus jitter
  • Explains amplification across layers and limits retries to one layer
  • Adds a retry budget or circuit breaker so retries stay a small fraction of traffic
  • Adds server-side load shedding with cheap rejections and Retry-After
  • Mentions bringing traffic back gradually while caches and connections warm
  • Notes that retried writes need idempotency

Revise: Timeouts and retries with jitter

10. A request passes through a gateway and four services before it reaches a database. How do you set the timeouts along that chain?

Seniorresiliencetimeoutsdeadlines

What the interviewer is really testing

Whether you reason about a request's total time budget instead of picking each timeout in isolation, and whether you account for retries, cancellation and work that continues after the caller has given up.

Show the model answer, follow-ups and checklist

Model answer

I would start from the outside. The user-facing target sets a total budget, say 2 seconds at the gateway. Everything below has to fit inside that, because work that finishes after the gateway has answered is wasted capacity.

Propagate a deadline, do not just configure timeouts. The gateway attaches the absolute deadline or the remaining time to the request. Each service passes it on. gRPC does this with its deadline mechanism, and with HTTP I would carry a header. Before each outgoing call, a service uses the smaller of two numbers: its own per-call timeout for that dependency and the time remaining, minus a small margin to send its own response. If too little time remains to do useful work, it fails immediately.

Per-call timeouts come from measurements. For each dependency I take its normal p99.9 and add a little. If the database answers in 50 ms at p99.9, its timeout is around 100 ms, not 5 seconds.

Timeouts must shrink down the chain. Even without propagation, the gateway’s timeout should exceed service one’s, which exceeds service two’s, and so on. If an inner timeout is longer than an outer one, the inner service keeps working for a caller that has gone.

Budget for retries. Attempts times per-attempt timeout, plus backoff, must fit within the caller’s budget. I retry at one layer only.

Cancel on expiry. When the deadline passes, cancellation flows down, and databases get a statement timeout so queries stop too.

Parallel fan-out shares one budget, since the calls overlap. Sequential calls consume it in turn, which is a reason to keep chains short.

Likely follow-ups

A downstream call legitimately takes 8 seconds at p99, but the user-facing budget is 2 seconds. What do you do?
Raising every timeout to 10 seconds only moves the waiting upstream. The operation does not fit a synchronous request, so make it asynchronous. Accept the request, return 202 with a status URL or push a notification when it finishes, and run the slow step from a queue. Caching or precomputing the result are the other options.
The deadline expires while a service is halfway through its work. What should happen?
Cancel what can be cancelled. Propagate cancellation to in-flight calls and set a statement timeout so the database also stops. A write that cannot be safely abandoned should be allowed to complete, and the operation must be idempotent so that the caller's later retry does not repeat it.
How do retries interact with the timeouts you chose?
All attempts plus backoff must fit inside the caller's own timeout. With a 1 second budget, two attempts of 300 ms and a 50 ms backoff use 650 ms. If the remaining deadline is shorter than one attempt, do not retry at all.
How do you pick the timeout for a single hop?
From the measured latency distribution of that dependency, usually a little above p99.9 in normal operation, then capped by the remaining deadline. A value that is too low creates false timeouts and retry load, so review it when the dependency's latency changes.

Common mistakes

  • Giving every hop the same timeout, so inner services keep working after outer ones have returned an error.
  • Using timeouts that grow as you go down the chain.
  • Forgetting that retries multiply the time a call can take.
  • Relying on library defaults, many of which are no timeout at all.
  • Timing out the caller without cancelling the downstream work or the database query.

A strong answer includes

  • Starts from an end-to-end budget tied to the user-facing latency target
  • Propagates a deadline and has each service check the remaining time
  • Makes effective timeouts shrink down the chain
  • Derives per-call timeouts from measured tail latency
  • Fits attempts and backoff inside the caller's budget
  • Cancels abandoned work, including database queries
  • Moves operations that cannot fit the budget to an asynchronous path

Revise: Timeouts and retries with jitter

11. One slow downstream dependency is making your whole service unresponsive. How do you isolate it, and when should a circuit breaker open?

Seniorresiliencecircuit-breakerbulkhead

What the interviewer is really testing

Whether you understand why slowness spreads through shared resources, can combine timeouts, bulkheads, breakers and fallbacks into one coherent design, and can justify breaker thresholds instead of quoting a library default.

Show the model answer, follow-ups and checklist

Model answer

A slow dependency is worse than a dead one. A dead one fails fast. A slow one holds each caller’s thread until the timeout, and if all dependencies share one pool, that pool fills with requests waiting on the slow one. Then nothing is left for healthy work, and my callers start to queue as well.

I would isolate it in four steps.

Timeout. Set from the dependency’s normal p99.9, not a default of 30 seconds. This bounds how long any one call holds a thread.

Bulkhead. Give this dependency its own bounded pool or a semaphore. I size it from peak calls per second times p99 latency, with headroom: 50 calls per second at 100 ms is 5 in flight, so 10 slots. When the slots are full, further calls are rejected at once. The worst case is now 10 threads lost, not all of them.

Circuit breaker. It should open on a failure rate over a sliding window, for example 50% of the last 50 calls, with a minimum number of calls so a quiet period cannot trip it on one error. Timeouts, connection errors and 5xx responses count. 4xx responses do not. While open, calls fail immediately for around 10 to 30 seconds, long enough for a restart or rollback. Then half-open lets a few trial calls through, closing on success and reopening on failure. The exact numbers should come from the dependency’s normal error rate and recovery time.

Fallback. For an optional dependency I serve a cached or default result, or hide the feature. For a critical one I fail fast with a clear error.

The breaker handles sustained failure, and the bulkhead covers the period before it opens and the case where the dependency is slow but not failing.

Likely follow-ups

The dependency is slow but still answers just inside the timeout, so the breaker never opens. What protects you?
The bulkhead. A fixed cap on concurrent calls limits how many threads the dependency can hold whatever its error rate. I would also lower the timeout towards its normal tail latency, and use a slow-call threshold if the library supports one, so that calls slower than a set duration count against the breaker.
Only one of the dependency's 30 instances is unhealthy. Does your breaker help?
Not a service-level one, since about 3% of calls fail and the threshold is never reached. That case belongs to the load balancer. Health checks and outlier detection eject the single bad instance, or the client keeps per-instance breakers.
Every instance of your service opens its breaker, then all of them close at the same moment and flood the recovering dependency. How do you avoid that?
Half-open already limits each instance to a few trial calls. Beyond that, add jitter to the open duration so instances probe at different times, ramp traffic up gradually after closing, and make sure the dependency sheds load itself so it is not relying on its callers' good behaviour.
The slow dependency is the payment provider. What is your fallback?
There is no honest substitute for a payment result. The choices are to fail fast with a clear message, or, if the business accepts it, to record the order as pending and complete the charge asynchronously with an idempotency key. Which one is right is a product decision as much as a technical one.
Would you implement the breaker in a client library or in a service mesh sidecar?
A library knows the application's fallbacks and which responses are real failures. A sidecar applies one policy across every language with no code change, but it can only return an error. Many teams use the mesh for connection limits and outlier detection and a library where a fallback is needed.

Common mistakes

  • Treating a slow dependency as less serious than a dead one, when slowness is what exhausts threads.
  • Adding a circuit breaker but no timeout, so calls hang and the breaker has no failures to count.
  • Opening on a small number of consecutive failures with no minimum call volume, which trips on noise.
  • Counting 4xx responses as failures of the dependency.
  • Describing the breaker with no answer for what the user sees while it is open.
  • Sharing one thread or connection pool across all dependencies.

A strong answer includes

  • Explains the mechanism of the cascade, blocked callers exhausting a shared pool
  • Sets a timeout based on the dependency's tail latency
  • Gives the dependency its own bounded pool or semaphore and sizes it from load and latency
  • Opens the breaker on a failure rate over a sliding window with a minimum number of calls
  • Describes open and half-open behaviour and the recovery probe
  • States a concrete fallback, or says plainly that there is none and fails fast
  • Distinguishes critical from optional dependencies
  • Mentions load shedding or outlier detection for the cases a breaker misses

Revise: Circuit breakers and bulkheads

12. The p99 latency of an endpoint doubled last week while the p50 did not move. How do you find the cause?

Seniorobservabilitylatencytracing

What the interviewer is really testing

Whether you debug methodically, using each signal for what it is good at, and whether you read the clue in the question, which is that only a subset of requests is affected.

Show the model answer, follow-ups and checklist

Model answer

The p50 not moving is the first clue. Most requests are as fast as before, so this is a subset of requests getting much slower, not a general slowdown. I am looking for what the slow ones have in common.

Scope it with metrics. When exactly did p99 change? I line that up with deploys, configuration changes, traffic shifts and dependency changes. Then I split the latency histogram by the dimensions I have: route, instance, region, version, and each downstream call. If one instance or one zone carries the regression, that is a very different problem from all of them carrying it.

Find where the time goes with traces. I pull traces from the slow tail, which is where tail-based sampling or exemplars pay off, and compare them with typical ones. The extra time will sit in a particular span: waiting for a connection, one database query, a downstream call, a lock, or a gap between spans that suggests queueing or a garbage collection pause.

Find out why with logs and resource metrics. For those trace ids, the logs give specifics such as the query, payload size and tenant. For the suspect resource I check utilisation and saturation: pool wait time, queue depth, GC pause time, CPU throttling.

Causes that typically hit only the tail:

  • a connection or thread pool that is occasionally exhausted
  • timeouts and retries against one bad replica
  • garbage collection pauses after a memory change
  • cache misses for a subset of keys
  • one large tenant or large payloads
  • a query that is slow only for certain parameters

Confirm. I form one hypothesis, test it with a rollback or a targeted change, and watch p99 return to its baseline before closing.

Likely follow-ups

The service has no distributed tracing. What do you do?
Get the same information more crudely. Put a request id in every log line, log the duration of each stage and each downstream call, and compare the attributes of slow and fast requests. Per-dependency latency histograms and a profiler on one instance cover most of what a trace would show.
The slow requests all come from one instance out of 20. What next?
Take it out of rotation to stop the user impact, then compare it with a healthy one. Look at the host for a noisy neighbour, failing disk or CPU throttling, at its configuration and version, and at whether the load balancer is sending it more traffic or the largest requests.
Slow traces show the request waiting 250 ms twice before a downstream call succeeds. What does that suggest?
A timeout followed by a retry. A delay close to a configured timeout value is the signature. The cause is in the downstream, often one bad replica or a pool that is briefly exhausted, and the retry is hiding failures as latency.
The regression appears only at peak traffic. What does that tell you?
It is a saturation problem. Some resource reaches its limit and requests queue, such as a connection pool, a thread pool, a lock or CPU. Saturation metrics for those resources, compared with the time p99 rises, should identify it, and a load test can reproduce it.

Common mistakes

  • Starting to guess at causes before establishing when it began and which requests are affected.
  • Looking at averages, which a regression in 1% of requests barely moves.
  • Averaging per-instance p99 values and concluding the fleet is fine.
  • Reading logs first across the whole fleet instead of using metrics and traces to narrow the search.
  • Stopping at the slow span without explaining why it is slow.
  • Not verifying the fix against the original metric.

A strong answer includes

  • Notes that an unchanged p50 means a subset of requests is slow
  • Establishes the start time and correlates it with deploys, config and traffic changes
  • Breaks latency down by bounded dimensions such as route, instance, region and version
  • Uses traces of slow requests to find the span where the time goes
  • Uses logs for those trace ids and resource saturation metrics to explain why
  • Names plausible causes of tail-only regressions
  • Verifies the fix by watching p99 return to baseline

Revise: Observability: logs, metrics and traces

13. How would you choose SLIs and SLOs for this service, and what would you page an engineer for?

Staffobservabilitysloalerting

What the interviewer is really testing

Whether you define reliability from the user's point of view, can turn it into precise, measurable indicators, and can design alerting that is both sensitive and quiet. At staff level, also whether you connect the error budget to how the team makes decisions.

Show the model answer, follow-ups and checklist

Model answer

I would start from what users do with the service, pick the two or three journeys that matter most, and define an indicator for each as a ratio: good events over valid events.

For a request-driven API that gives two SLIs:

  • Availability: the share of valid requests answered without a server error. I need to say what “valid” means. Server errors and timeouts count against us. Most 4xx responses are the client’s mistake and do not.
  • Latency: the share of requests answered within a threshold, such as 300 ms. A ratio, not an average and not a single percentile, because ratios combine cleanly over time windows.

A data pipeline would use freshness and correctness instead, and a storage system durability.

I measure at the load balancer where possible, because a server that is down reports no failures.

For the SLO I pick a target that reflects what users need and what the system has achieved, never 100%. Say 99.9% over a rolling 30 days. That leaves an error budget of 0.1%, about 43 minutes of full outage.

For alerting I page on burn rate, which is how fast the budget is being spent, using the multi-window pattern from Google’s SRE Workbook:

  • page at a burn rate of 14.4 over one hour, confirmed by the last 5 minutes
  • page at 6 over six hours, confirmed by the last 30 minutes
  • open a ticket at 1 over three days

The long window makes the alert meaningful and the short one makes it clear quickly once the problem is fixed. Fast, severe incidents page within minutes, and slow leaks are still caught.

Cause-based signals such as CPU and queue depth go on dashboards. And the budget needs a policy: when it is spent, the team slows releases and works on reliability.

Likely follow-ups

Why not page on high CPU or memory?
They are causes, and often not even that. A busy machine can be perfectly healthy, and many outages happen with CPU idle. Paging on them produces noise and still misses real incidents. They stay on dashboards for diagnosis, with tickets for the few that reliably predict trouble, such as a disk filling.
The service receives about 10 requests an hour. How does burn-rate alerting cope?
Badly, because one failure is 10% of an hour's traffic. Options are longer windows, a minimum number of failed requests before alerting, and synthetic probes that generate steady traffic to measure. It may also be right to give such a service a looser objective.
Where do you measure the SLI?
As close to the user as is practical. Server-side metrics miss requests that never arrived or that the process was too broken to count. The load balancer sees those. Client-side measurement is closest to the truth but noisy and outside your control. I would usually alert on load balancer data and watch client data.
A dependency you call on every request offers 99.9%. Can you promise 99.99%?
Only if you can survive its failure. In a serial dependency, availabilities multiply, so you cannot exceed it by simply calling it. A cache, a fallback or a redundant provider can break that link, and the objective should be set after deciding which of those you will build.
What happens when the error budget is used up?
That should be agreed beforehand in an error budget policy. A typical one pauses risky releases and moves engineering time to reliability work until the service is back within its objective. Without a consequence, the SLO is only a dashboard.

Common mistakes

  • Choosing indicators from what is easy to measure, such as CPU, instead of what users experience.
  • Using average latency as an indicator.
  • Setting a 100% target, or a number with no basis in user need or history.
  • Leaving "good" and "valid" requests undefined, for example whether client errors count.
  • Paging on a raw error-rate threshold over one short window, which is either noisy or slow.
  • Having an objective with no agreed consequence for missing it.

A strong answer includes

  • Starts from critical user journeys
  • Defines each SLI as a ratio of good events to valid events and says what counts
  • Expresses latency as the share of requests under a threshold
  • Chooses a target below 100% and states the resulting error budget
  • Measures at the load balancer or client, not only inside the server
  • Pages on burn rate using more than one window, with slow burns going to tickets
  • Describes what the team does when the budget is spent

Revise: Observability: logs, metrics and traces

14. Would you use server-side sessions or JWTs for this application, and how would you log a user out of every device immediately?

Mid-levelsecurityauthenticationjwt

What the interviewer is really testing

Whether you can compare the two on their real trade-off, revocation against a lookup per request, without treating JWT as automatically modern or sessions as outdated, and whether you know how revocation is actually built.

Show the model answer, follow-ups and checklist

Model answer

The real difference is where the state lives. A server-side session keeps it on the server and gives the client an opaque id. A JWT puts signed claims in the client’s hands so that services can verify them without a lookup. That one choice decides how revocation works.

For a first-party web application on one domain, I would use server-side sessions: a random id in an HttpOnly, Secure, SameSite cookie and the session in Redis. The lookup costs around a millisecond, and logging out everywhere is trivial. Index sessions by user id and delete all of that user’s records. The next request from any device fails.

If the system has many services, mobile clients or third-party API consumers, I would use JWT access tokens that live 5 to 15 minutes, plus refresh tokens that are stored server-side and rotated on each use. Services verify access tokens locally with the issuer’s public key.

Logging out everywhere then has two parts:

  1. Revoke all of the user’s refresh tokens. No device can obtain a new access token.
  2. Deal with access tokens already issued. Either accept that they work for a few more minutes, or, where “immediately” is a hard requirement, store a per-user “tokens issued before this time are invalid” value in a cache that the gateway checks. A denylist of token ids with a TTL equal to the token’s remaining life also works.

Step 2 puts a lookup back on the request path, which is the honest cost of instant revocation with tokens.

A common middle ground is an opaque session at the edge, which the gateway exchanges for a short-lived internal JWT. Revocation happens in one place and services still verify locally.

Likely follow-ups

If you check a denylist on every request, what has the JWT bought you?
Less than the stateless story suggests, and it is fair to say so. The denylist is still much smaller than a session store, because it holds only revoked tokens and only until they expire, and it can be replicated to each service or cached locally. Services also still read claims without a lookup. But if every request needs instant revocation, opaque sessions are the simpler design.
Where should a browser application keep the token?
In a cookie marked HttpOnly, Secure and SameSite, so that injected scripts cannot read it. That brings back the need for CSRF protection, which SameSite and anti-forgery tokens provide. Keeping tokens in localStorage exposes them to any cross-site scripting bug. A backend-for-frontend that holds the tokens server-side is the stricter option.
An administrator removes a user's role, but the user's token still contains it. What happens?
The claim stays valid until the token expires, so the user keeps the permission for up to one token lifetime. Short lifetimes bound the gap. For sensitive actions, check the permission against the source of truth instead of trusting the claim.
How do you rotate the JWT signing key without logging everyone out?
Publish the new public key in the issuer's key set under a new key id, start signing with the new private key, and keep the old public key published until every token signed with it has expired. Verifiers select the key by the kid in the header and refetch the key set when they see one they do not know.

Common mistakes

  • Claiming JWTs are more secure than sessions, when the difference is where the state lives.
  • Saying logout "deletes the token", which only removes the client's copy.
  • Issuing long-lived access tokens with no revocation plan.
  • Storing sensitive data in the JWT payload, which is readable by anyone who holds the token.
  • Ignoring where the browser stores the credential and the XSS and CSRF consequences.

A strong answer includes

  • States the core trade-off of instant revocation against a lookup on each request
  • Chooses one for the application described and gives the reason
  • Uses short-lived access tokens with server-side refresh tokens if choosing JWTs
  • Explains logout everywhere for the chosen design
  • Offers a denylist or per-user cut-off time for immediate revocation and admits its cost
  • Covers cookie flags or browser storage
  • Mentions the hybrid of an opaque token at the edge and internal JWTs

Revise: Authentication and authorization: sessions, OAuth and JWT

15. Walk me through what happens when a user taps "Sign in with Google" in your mobile app.

Mid-levelsecurityoauthoidc

What the interviewer is really testing

Whether you understand the authorization code flow as a set of defences, each parameter answering a specific attack, and whether you can tell OAuth (delegated access) from OpenID Connect (login) and an access token from an ID token.

Show the model answer, follow-ups and checklist

Model answer

This is OpenID Connect, which is a login layer on top of the OAuth 2.0 authorization code flow. Google is the authorization server, the user is the resource owner and my app is the client. Because a mobile app cannot keep a secret, it is a public client and uses PKCE.

  1. Prepare. The app generates a random code verifier and keeps it in memory. It hashes it with SHA-256 to make the code challenge. It also generates a random state and a nonce.
  2. Authorization request. The app opens the system browser at Google’s authorization endpoint with its client id, redirect URI, the scopes openid email profile, the state, the nonce, and the code challenge with method S256.
  3. Authentication and consent. The user signs in on Google’s page and approves. My app never sees the password.
  4. Redirect with a code. Google redirects to my registered redirect URI with a short-lived, single-use authorization code and the state. The app checks that the state matches.
  5. Token request. The app posts the code and the original code verifier directly to the token endpoint over TLS. Google hashes the verifier and compares it with the stored challenge. If another app intercepted the code, it has no verifier and gets nothing.
  6. Tokens. Google returns an ID token, an access token and possibly a refresh token. The app checks that the nonce inside the ID token is the one it sent.

Then my own system takes over. The app sends the ID token to my backend, which verifies the signature against Google’s published keys and checks the issuer, the expiry and that the audience is my app’s client id. It finds or creates the user by the stable sub claim and issues my own session.

The ID token tells me who logged in. The access token is for calling Google’s APIs, and I would not use it as proof of identity.

Likely follow-ups

Why not have the authorization server return the tokens directly in the redirect, as the implicit flow did?
Tokens in a redirect URL can end up in browser history, logs and referrer headers, and nothing binds them to the client that asked. The implicit flow also could not safely issue refresh tokens. Current security guidance (RFC 9700) says not to use it, and the code flow with PKCE replaces it.
What is the difference between state, the PKCE verifier and the nonce?
State ties the redirect back to the browser session that started the flow, which stops cross-site request forgery. The PKCE verifier ties the code to the client instance that requested it, which defeats a stolen or injected code. The nonce ties the ID token to this login request, so a token from another login cannot be replayed.
Why can the mobile app not simply use a client secret?
Anything shipped inside an app binary can be extracted, so it is not a secret. That is the definition of a public client. PKCE replaces the static secret with a fresh one generated for each login, which never leaves the device until the token request.
Why the system browser and not a web view embedded in the app?
An embedded web view lets the host app read what the user types and the cookies, which defeats the point of keeping credentials away from the app. It also cannot share the user's existing signed-in session. RFC 8252, the best practice for native apps, requires an external user agent.
The access token expires an hour later. What happens?
The app sends its refresh token to the token endpoint and receives a new access token, with no user interaction. With rotation it also gets a new refresh token and the old one is invalidated, so a stolen refresh token is detected when it is used a second time.

Common mistakes

  • Describing the flow as "the app sends the password to Google".
  • Leaving out PKCE or state, or not being able to say what either prevents.
  • Sending the ID token to APIs as a credential, or treating an access token as proof of who logged in.
  • Accepting an ID token without checking its signature, issuer, audience and expiry.
  • Proposing the implicit flow or the password grant for a new application.

A strong answer includes

  • Identifies this as OpenID Connect on top of the OAuth 2.0 authorization code flow
  • Names the four roles and who plays each
  • Generates a code verifier and sends only its hash in the authorization request
  • Has the user authenticate at the authorization server, never in the app
  • Returns a short-lived, single-use code through the browser and exchanges it on a direct connection
  • Sends the verifier with the token request and explains why a stolen code is useless
  • Validates the ID token and distinguishes it from the access token
  • Explains state and exact redirect URI matching

Revise: Authentication and authorization: sessions, OAuth and JWT

16. How would you encrypt sensitive customer data at rest, and how do you rotate the keys without downtime?

Staffsecurityencryptionkms

What the interviewer is really testing

Whether you start from a threat model, understand that the hard part is key management and not the cipher, and can design rotation as a routine, online operation. At staff level, also whether you think about every copy of the data and the operational dependency on the KMS.

Show the model answer, follow-ups and checklist

Model answer

I would begin with the threat. Encrypted volumes and database-level encryption stop someone who gets the disks, files or snapshots, and I would turn those on everywhere as a baseline. They do nothing against someone reading through the live database, so for the most sensitive fields I add application-level encryption.

Design. I use envelope encryption. Each tenant has a data key. The service encrypts fields locally with AES-256-GCM and a unique nonce per value. The data key is wrapped by a key encryption key held in a KMS and never exported. Each row stores the ciphertext, the nonce, and the id and version of the key used. Wrapped data keys live in their own table. Only this service’s identity may call decrypt on the KMS key, and every call is logged. Plaintext data keys are cached in memory for a few minutes to keep the KMS off the hot path.

Rotating the key encryption key is a KMS operation. A new version becomes current for wrapping, and old versions remain available for unwrapping. If policy requires it, a background job re-wraps the data keys, which rewrites a few kilobytes and not the data.

Rotating data keys is done online in four stages:

  1. Create a new key version and start using it for all writes.
  2. Reads choose the key by the version stored on the row, so old and new coexist.
  3. A background job re-encrypts old rows in small batches. It is throttled, resumable and safe to run twice.
  4. When no row references the old version, retire it.

There is no downtime because both versions are readable throughout.

Two caveats. Copies of the data in replicas, backups, caches, search indexes and logs need the same treatment or must never receive plaintext. And if a key has actually leaked, rotation is not enough: the affected data must be re-encrypted and treated as exposed.

Likely follow-ups

You need to look a user up by an email address that is now encrypted. How?
Add a second, indexed column holding a keyed hash (HMAC) of the normalised email, using a key separate from the encryption key. Lookups hash the input and match on that column. It supports equality only and reveals when two rows share a value, so it is a deliberate, limited leak. Range and substring queries are not possible this way.
The KMS is unreachable. What does your service do?
Data keys cached in memory keep recent reads and writes working until the cache expires, so the cache lifetime is a trade between availability and exposure. Past that, the service cannot decrypt and should fail clearly instead of serving errors silently. Multi-region keys and treating the KMS as a critical dependency in capacity planning reduce the risk.
A user asks for their data to be erased, but it also exists in months of backups. How does your design help?
With a data key per user or tenant, destroying that key makes every copy of their ciphertext unreadable, including copies in backups that cannot be edited. This is crypto-shredding. It only works if the key was never stored alongside the backups.
Why not rely on the database's transparent encryption or encrypted volumes alone?
They protect against someone obtaining the files or disks. Anyone who reaches the data through the running database sees plaintext, including a SQL injection attack, an over-privileged account or an analytics export. If those are in the threat model, the sensitive fields need application-level encryption.
One data key for everything, or one per record?
It is a trade between isolation and overhead. One key for everything means one leak exposes all data and re-encryption is enormous. One per record gives the best isolation but more storage and more KMS calls. One per tenant or per user is a common middle, and it also enables per-tenant erasure.

Common mistakes

  • Naming AES-256 and stopping, without saying where the key is kept or who can use it.
  • Storing the encryption key in configuration, source control or the same database as the data.
  • Describing rotation as re-encrypting the whole dataset in one maintenance window.
  • Not storing a key identifier with each ciphertext, which makes rotation impossible later.
  • Forgetting replicas, backups, caches, search indexes and logs that hold copies of the same data.
  • Treating rotation as a sufficient response to a key that has leaked.

A strong answer includes

  • States the threats and which layer answers each
  • Uses volume or database encryption as a baseline and application-level encryption for sensitive fields
  • Describes envelope encryption with data keys wrapped by a key held in a KMS
  • Stores the wrapped key and key version with the ciphertext
  • Restricts and audits who can call decrypt
  • Rotates the key encryption key by versioning, with only wrapped keys rewritten
  • Rotates data keys with dual-read and a throttled, resumable background re-encryption
  • Accounts for backups, replicas and derived copies, and for KMS availability

Revise: Encryption at rest and in transit