All modules

Networking: interview questions

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

1. What happens when you type a URL into your browser and press Enter?

Mid-leveldnstcptls

What the interviewer is really testing

Whether you hold a correct end-to-end model of a request, from naming through transport and encryption to routing and the application, and whether you can choose where to go deep instead of reciting every layer at the same shallow level.

Show the model answer, follow-ups and checklist

Model answer

I will go through it in order and then go deeper wherever is most useful to you.

  1. URL and caches. The browser parses the URL and decides on HTTPS. It checks whether it already has a fresh cached response, or an open connection to that host it can reuse.
  2. DNS. With no cached address, the operating system’s stub resolver asks a recursive resolver. On a cold cache that resolver asks a root server, the TLD server and the domain’s authoritative server, then caches the answer for its TTL. The answer is often already a routing decision: a nearby CDN edge chosen by GeoDNS, or an anycast address.
  3. Connection. A TCP three-way handshake costs one round trip. The TLS 1.3 handshake costs one more: the server sends its certificate chain, the browser validates it against its trust store, and both derive session keys. They agree on HTTP/2 during that handshake. If the browser knows the site supports HTTP/3, it uses QUIC and gets transport and encryption set up in a single round trip.
  4. Request. The browser sends GET / with headers and cookies. It arrives at a CDN edge or a load balancer, which terminates TLS. Cached content is answered there. Anything else goes to a healthy application server, possibly through an API gateway that checks authentication and rate limits.
  5. Application. The server runs the handler, reads from a cache or database, and returns a status, headers that say how the response may be cached, and a body.
  6. Render. The browser parses the HTML, discovers stylesheets, scripts and images, and fetches them, mostly as parallel streams on the same connection. Then it lays out the page and runs scripts.

On a cold start that is roughly four round trips before the first byte: DNS, TCP, TLS and the request. That is why connection reuse, CDNs and HTTP/3 matter so much to users far from the servers.

Likely follow-ups

Which of those steps are skipped on a second visit a minute later?
Most of them. The DNS answer is cached in the browser, the operating system and the resolver. The connection is probably still open, so there is no TCP or TLS handshake, and if it closed, TLS session resumption shortens the new one. Static assets come from the browser cache with no request at all while they are fresh, or with a cheap conditional request that returns 304.
The user typed only the domain. How does the browser know to use HTTPS?
If the site has sent a Strict-Transport-Security header before, or is on the browser preload list, the browser upgrades to HTTPS before sending anything. Modern browsers also increasingly try HTTPS first for typed addresses. Otherwise the first request goes over plain HTTP and the server redirects, which is the window HSTS exists to close.
Where does the server learn the client IP address, and where can that go wrong?
The CDN or load balancer sees the real source address. An L7 proxy opens its own connection to the backend, so the backend sees the proxy address and must read the original from a header such as X-Forwarded-For, or from the PROXY protocol at L4. That header is only trustworthy when it was set by your own proxy, because any client can send one.
The page loads in 200 ms near the data centre and 3 seconds from another continent. Where do you look first?
At round trips multiplied by distance, since server time is the same for both users. I would count how many round trips happen before the first byte and during asset loading, then check whether connections terminate near the user at a CDN, whether assets are cached at the edge, and whether connections are being reused over HTTP/2 or HTTP/3.

Common mistakes

  • Spending the whole answer on ARP, Ethernet frames and routing tables and never reaching the load balancer or the application.
  • Listing layers with no sense of cost, never mentioning round trips or caching.
  • Leaving out TLS, or describing it before the TCP handshake.
  • Saying DNS returns the IP of "the server", when it is normally a CDN edge or a load balancer.
  • Forgetting that the browser then fetches dozens of sub-resources, mostly over the same connection.

A strong answer includes

  • DNS resolution through a recursive resolver, with caching and TTLs
  • TCP handshake, then TLS handshake with certificate validation, or QUIC doing both in one round trip
  • HTTP version negotiation and connection reuse
  • A CDN or load balancer in front of the servers, and where TLS terminates
  • The application and data tier in a sentence or two
  • The browser parsing HTML and fetching sub-resources, using its cache
  • A count of round trips, or another clear statement of where the latency comes from
  • An offer to go deeper on one part instead of equal weight everywhere

Revise: DNS

2. Your primary region fails and you repoint DNS at the standby. Why are some users still seeing errors ten minutes later, and what would you change?

Seniordnsfailovermulti-region

What the interviewer is really testing

Whether you understand that a DNS change spreads through caches you do not control, can estimate failover time from its parts, and know the alternatives when minutes are too slow.

Show the model answer, follow-ups and checklist

Model answer

Nothing is wrong with the change. DNS failover takes detection time, plus the TTL, plus a tail, and the users still broken are in the tail.

Take typical numbers. Health checks every 10 seconds with three failures needed is 30 seconds to detect. A 60 second TTL means resolvers that fetched the record just before the change serve it for another minute. So about 90 seconds for well-behaved clients. The rest are slower for three reasons:

  • Open connections. A client with a keep-alive connection or a pool does not look the name up again until the connection fails, and without sensible timeouts it may hang on a half-dead region.
  • Client-side caches. Some runtimes, HTTP libraries and mobile apps resolve once and keep the address far beyond the TTL.
  • Resolvers that stretch TTLs. Some enforce a minimum.

What I would change, in order:

  1. Tune what exists. Keep the TTL at 30 to 60 seconds before any incident, including on every CNAME in the chain, since a cache honours the TTL it was given.
  2. Fix the clients I control. Mobile apps and internal services get connect and read timeouts, and re-resolve when a connection fails.
  3. Take DNS out of the fast path. Put an anycast address or a global load balancer in front, so failover is a routing change that takes seconds and the address never changes.
  4. Prefer active-active. If both regions always serve traffic, losing one removes capacity and nothing has to switch. Each region then needs headroom to absorb the other.

Moving traffic is also only half the job. The standby is useful only if the data is there, so I would state the replication lag I am accepting. DNS failover remains a reasonable tool when a few minutes of partial outage is acceptable. It is the wrong tool for a recovery target measured in seconds.

Likely follow-ups

Why not set the TTL to one second?
Some resolvers enforce their own minimum and ignore very low values. Every lookup that misses the cache adds latency to a real user request, and query volume, cost and your dependence on the DNS provider all go up. Below about 30 seconds the gain is small, because the clients still broken are the ones ignoring the TTL anyway.
How is failover different with anycast?
The IP address never changes, so there is nothing cached to expire. The failed site stops announcing the route, or the provider stops forwarding to it, and within seconds new packets reach the next nearest site. Connections that were open to the failed site still break and must be re-established.
What goes wrong in active-passive that active-active avoids?
The standby is cold. Its caches are empty, autoscaling is at its minimum, connection pools are closed, and the failover procedure itself is rarely exercised. With active-active every region serves real traffic all the time, so capacity and configuration are continuously proven. The price is headroom in every region and a data layer that copes with more than one region taking writes, or a clear primary.
What if the DNS provider itself goes down?
Resolvers keep answering from cache until TTLs expire, and then users cannot resolve the name at all, so very low TTLs make this failure worse. The defence is a second provider serving the same zone, with both listed in the NS records and automation keeping the two in step.

Common mistakes

  • Claiming that DNS failover is instant, or that it takes exactly one TTL.
  • Lowering the TTL during the incident and expecting it to help caches that already hold the old record.
  • Forgetting open connections and clients that cache addresses for the life of the process.
  • Discussing only traffic, and never asking whether the standby has the capacity and the data.

A strong answer includes

  • Breaks failover time into detection, TTL and a tail of slow clients
  • Gives a concrete estimate with stated check interval, threshold and TTL
  • Names at least two reasons clients outlast the TTL
  • Proposes anycast or a global load balancer when failover must take seconds
  • Compares active-active with active-passive, including capacity headroom
  • Mentions data replication lag as the other half of a regional failover

Revise: DNS

3. You are building a fast-paced multiplayer game. Would you send game state over TCP or UDP, and what would you have to build yourself?

Seniortcpudprealtime

What the interviewer is really testing

Whether you choose a transport from the properties of the data, above all whether late data is still useful, and whether you know what you take on when you leave TCP.

Show the model answer, follow-ups and checklist

Model answer

I would split the traffic by what it needs, because a game sends two different kinds of data.

State updates such as player positions go out 20 to 60 times a second, and each one replaces the last. Over TCP, one lost packet blocks everything behind it until the retransmission arrives, at least a round trip later. Newer positions sit in the kernel while the player sees a freeze and then a burst. Late data here is worthless, so I would send it over UDP: number each update, let the receiver drop anything older than what it has already applied, and smooth over gaps on the client by interpolating.

Events that must arrive, such as “item purchased”, “match ended” and chat, need reliability and usually ordering. Either I add acknowledgements and retransmission for those messages only, on the same UDP flow, or I send them on a separate TCP or WebSocket connection. Login, matchmaking and payments are ordinary HTTPS.

On UDP I own everything TCP was doing:

  • sequence numbers, and acknowledgement and retransmission for the reliable subset;
  • a cap on send rate that backs off under loss, so the game does not flood a weak link;
  • a session handshake with a token, so that sources cannot be spoofed, and encryption;
  • keep-alive packets, because NAT devices forget idle UDP flows quickly;
  • datagrams of about 1,200 bytes or less, to avoid fragmentation;
  • a fallback over TCP for networks that block UDP.

That is a lot to get right, so I would not write it from scratch. QUIC offers reliable streams and unreliable datagrams on one connection, WebRTC data channels do the same for browsers, and game networking libraries such as ENet package these features.

The choice follows from one question: is late data still worth having? For a turn-based game the answer is yes, and I would simply use TCP.

Likely follow-ups

Browsers cannot open raw UDP sockets. What do you do for a web client?
Use WebRTC data channels configured as unordered and unreliable, or WebTransport datagrams over HTTP/3 where the browser supports them. Fall back to a WebSocket, which is TCP, and accept occasional stalls on bad networks.
How do you stop your UDP protocol being used in amplification attacks?
Never send a large reply to an address you have not verified. Have the client echo a token issued by the server before the server allocates state or sends more than it received, and keep replies to unauthenticated packets no larger than the request.
Why not open several TCP connections to dodge head-of-line blocking?
It limits the damage of one loss to one connection, but the delayed message still waits for a retransmission nobody wanted. Losses on the same path also tend to come together, so several connections often stall at once, and you pay for more handshakes and more state.
The game is online chess. Does your answer change?
Yes. Every move must arrive, in order, and a delay of a hundred milliseconds is invisible to the players. That is exactly what TCP provides, so I would use a WebSocket. Choosing UDP there means rebuilding TCP for no benefit.

Common mistakes

  • Saying "UDP is faster" without explaining that the gain is the absence of waiting for retransmissions.
  • Sending purchases, chat and match results over an unreliable channel.
  • Forgetting congestion control, NAT keep-alives and networks that block UDP.
  • Giving the same answer for a turn-based game.

A strong answer includes

  • Separates data that is useless when late from data that must arrive
  • Explains head-of-line blocking as the reason TCP hurts state updates
  • Lists what must be built on UDP, including sequencing, selective reliability, rate control, keep-alives and encryption
  • Offers QUIC, WebRTC or an existing library before a hand-written protocol
  • Has a fallback for networks that block UDP
  • Says when TCP is the right answer

Revise: TCP vs UDP

4. Calls from service A to B have a median of 5 ms and a p99 just over one second, yet B handles every request in under 10 ms. Where is the second going?

Seniortcpdebuggingconnection-pooling

What the interviewer is really testing

Whether you can reason about latency below the application layer, in connection setup, retransmission timers and queues that the server never measures, and whether you investigate before proposing a fix.

Show the model answer, follow-ups and checklist

Model answer

B’s timer starts when a request reaches its handler, so everything before that is invisible to it: queueing on A, connection setup, the network, and B’s own accept queue. The time is being lost in one of those.

“Just over one second” is a clue. On Linux, the first retransmission of an unanswered SYN happens after one second, because a new connection has no round-trip estimate yet. So my first hypothesis is that A opens a new connection for some requests, and now and then the SYN, or the reply to it, is dropped. That costs a second plus the normal 5 ms.

Two questions follow.

Why is A opening connections at all? The candidates are no keep-alive, a pool too small for bursts so the overflow dials new connections, or an idle timeout mismatch where B or a load balancer closes connections the pool believes are live.

Why are handshake packets being dropped? B’s accept queue may be overflowing during bursts because the application is not accepting fast enough. A firewall or connection-tracking table on the path may be full. Or it is plain packet loss.

To confirm, I would:

  • split A’s latency by new versus reused connection, with connect time measured separately;
  • read the kernel counters on both hosts for SYN retransmissions and listen queue overflows (netstat -s shows both);
  • take a short packet capture if the counters are unclear.

Fixes depend on what that shows. Most likely: pool and reuse connections, sized for peak concurrency. Make A’s idle timeout shorter than B’s. Raise B’s listen backlog and check that it accepts promptly. And set a connect timeout far below one second, with a retry to another instance.

If the evidence showed time spent waiting for a pooled connection instead, the problem would be pool size or a concurrency limit, and the fix would be different. I would not change anything until I knew which.

Likely follow-ups

Suppose the p99 were about 200 ms instead of one second. Would your diagnosis change?
Probably. About 200 ms matches the minimum retransmission timeout on Linux for an established connection, which you hit when the last packet of a request or response is lost and nothing follows it to trigger a fast retransmit. A step of about 40 ms would suggest delayed acknowledgements interacting with small writes. Latencies that sit on round numbers usually point at a timer.
Why can B not see this in its own metrics?
B starts its timer when the handler begins and stops it when the response is written. Time spent establishing the connection, waiting in the kernel before the application accepts it, or queuing for a free connection in the pool on A happens outside that window. You need measurements on the client side, ideally traces with separate spans for pool wait and connect.
How could mismatched idle timeouts produce this?
If a load balancer or B closes idle connections after 60 seconds while the pool on A keeps them for five minutes, A will sometimes send on a connection that is already closed. The request fails and is retried on a fresh connection, which adds setup time and occasionally an error. Set the idle timeout on the client lower than on the server side.
What connect timeout would you set between two services in the same data centre?
The round trip is well under a millisecond, so a connect timeout of tens of milliseconds is generous. On expiry, retry against a different instance, which avoids waiting a full second for a lost SYN. Cap the retries so that an overloaded B is not hit harder.

Common mistakes

  • Blaming the code or garbage collection in B after its metrics have already ruled that out.
  • Not noticing that one second is a timer value.
  • Proposing more servers before finding where the time goes.
  • Forgetting the client side, including the connection pool and its queue.

A strong answer includes

  • States that server-side timing excludes connect, queueing and network time
  • Recognises a round-number latency as the signature of a retransmission timer
  • Proposes new connections plus dropped SYNs as the hypothesis, with possible causes
  • Says how to confirm it, with client-side connect timing, kernel counters or a packet capture
  • Fixes it with pooling, aligned idle timeouts, backlog tuning and short connect timeouts

Revise: TCP vs UDP

5. What is head-of-line blocking, and did HTTP/2 fix it?

Mid-levelhttphttp2http3

What the interviewer is really testing

Whether you can tell the application-level queue from the transport-level one, and explain how each HTTP version moved the problem instead of reciting feature lists.

Show the model answer, follow-ups and checklist

Model answer

Head-of-line blocking is when the first item in a queue holds up everything behind it, even though the later items are ready. HTTP has had it at two different layers.

HTTP/1.1 has it at the application layer. A connection carries one request and response at a time, so a slow response blocks every request waiting behind it. Pipelining tried to help by sending requests back to back, but responses still had to return in order, so it changed little. Browsers worked around it by opening up to six connections per host.

HTTP/2 fixed that layer. It splits requests and responses into frames tagged with a stream number and interleaves them on one connection. A slow response no longer blocks the others, and one connection is enough.

But HTTP/2 still runs on TCP, and TCP delivers one ordered stream of bytes. If a single packet is lost, TCP holds back everything after it until the retransmission arrives, whichever HTTP/2 stream those bytes belong to. So the answer is: HTTP/2 fixed head-of-line blocking in HTTP and exposed it in the transport. All streams stall together for a round trip or more.

HTTP/3 fixes the transport layer by replacing TCP with QUIC, which runs over UDP and has streams built in. QUIC retransmits lost data, but it orders each stream separately. A lost packet delays only the streams whose data it carried.

How much this matters depends on the network. On a clean wired link losses are rare, and HTTP/2 is nearly as good as HTTP/3. On a mobile network with real loss, the gap shows up in tail latency. That is why I would use HTTP/3 between users and the edge, and be content with HTTP/2 inside a data centre.

Likely follow-ups

When can HTTP/2 be slower than HTTP/1.1?
On a network with noticeable packet loss. Every loss stalls all the streams on the single HTTP/2 connection, and the one congestion window is cut. With six HTTP/1.1 connections, a loss stalls one of them and the other five carry on.
Does HTTP/3 remove head-of-line blocking completely?
It removes it between streams. Within one stream data is still ordered, so a lost packet delays the rest of that response. Header compression can also make a stream wait briefly for table updates sent on another stream, which QPACK lets the endpoints bound.
Why build QUIC instead of fixing TCP?
Ordered delivery is what TCP is, and TCP lives in operating system kernels and in middleboxes that inspect and sometimes rewrite it, so changes take many years to deploy or are stripped on the way. QUIC runs over UDP in user space with most of its header encrypted, so it ships with the application and middleboxes cannot interfere with what they cannot read.
Where else do you see head-of-line blocking in system design?
Anywhere one slow item at the front of a FIFO holds up the rest. A single worker on a queue, a Kafka partition stuck on a message that keeps failing, and a connection pool of size one are all examples. The fixes are the same in spirit: more independent lanes, or moving the stuck item aside.

Common mistakes

  • Saying HTTP/2 eliminated head-of-line blocking, with no mention of TCP.
  • Confusing pipelining with multiplexing.
  • Describing HTTP/3 as "HTTP over UDP" as if it were unreliable.
  • Giving the mechanism but not when it matters, which is on lossy, high-latency networks.

A strong answer includes

  • Defines head-of-line blocking as one item at the front delaying everything behind it
  • HTTP/1.1 allows one request at a time per connection, and browsers work around it with six connections
  • HTTP/2 multiplexes streams and removes the application-level queue
  • TCP ordered delivery means one lost packet stalls all HTTP/2 streams
  • HTTP/3 over QUIC orders each stream independently
  • Says where it matters and where it does not

Revise: HTTP/1.1 vs HTTP/2 vs HTTP/3

6. The mobile team wants HTTP/3 enabled for the API. What do you expect to gain, what could go wrong, and how would you roll it out?

Staffhttp3quicrollout

What the interviewer is really testing

Whether you can evaluate a protocol change as an engineering decision, with the expected benefit by user segment, the operational risks, a way to measure and a way back, and not as a feature list.

Show the model answer, follow-ups and checklist

Model answer

What I expect to gain. The benefit is uneven, so I would set expectations by segment. Users on lossy or high-latency mobile networks gain most. A lost packet no longer stalls every in-flight request, a new connection takes one round trip to set up where TCP plus TLS 1.3 takes two, and a connection survives the switch from Wi-Fi to mobile data without new handshakes. Users on good Wi-Fi with a warm connection will see almost nothing. I expect the improvement in p95 and p99, and little in the median.

What could go wrong.

  • Some networks block or throttle UDP. Clients must fall back to HTTP/2 automatically.
  • QUIC costs more CPU per byte at the edge than TCP with TLS, so capacity needs checking.
  • Load balancers must route by connection ID, or migration breaks.
  • 0-RTT data can be replayed, so it is a separate decision.
  • Debugging is harder. Packet captures show little, and we would rely on endpoint logs and metrics.
  • UDP on port 443 is new attack surface for floods.

How I would roll it out.

  1. Enable HTTP/3 at the CDN or edge proxy only. The origin keeps speaking HTTP/2, so nothing behind the edge changes.
  2. Advertise it with Alt-Svc to a small percentage of clients, with a short lifetime on the advertisement so that withdrawing it takes effect quickly.
  3. Compare cohorts on connection setup time, request latency at p50, p95 and p99, error and timeout rates, and how often clients fall back. Split by network type and country.
  4. Watch CPU at the edge, then ramp in steps.
  5. Keep 0-RTT off at first. Consider it later for idempotent requests only.

Rollback is cheap: stop advertising and clients return to HTTP/2. That, plus doing it at the edge, is what makes this a low-risk experiment and not a migration.

Likely follow-ups

How does a client find out that the server speaks HTTP/3?
From an Alt-Svc header on an HTTP/1.1 or HTTP/2 response, or from an HTTPS record in DNS. The client remembers the advertisement for its stated lifetime and tries QUIC on later connections, normally racing it against TCP so that a blocked UDP path costs little.
Would you enable 0-RTT?
Not on day one. Later, and only for idempotent requests. The edge should mark requests that arrived as early data, for example with the Early-Data header, so the origin can refuse anything that changes state with a 425 and have the client retry after the handshake. The gain is one round trip on resumed connections, which mostly helps app start-up.
What has to change at the load balancer?
QUIC is UDP, so the L4 tier must forward UDP on port 443 and firewalls must allow it. To support connection migration, packets must be routed by QUIC connection ID, consistently across all balancer instances. Hashing on addresses and ports works until a client changes network, and then the connection lands on a server that does not know it.
The experiment shows no change in median latency. Has the project failed?
Not necessarily. The gains concentrate in the tail, on lossy or high-latency networks, and on new connections. I would look at p95 and p99, split by network type and country, and at timeout and retry rates. If those have not moved either, then not shipping it is a perfectly good outcome.

Common mistakes

  • Promising a speed-up for every user.
  • Proposing HTTP/3 between internal services as part of the same change.
  • Forgetting the fallback for networks that block UDP.
  • Having no plan to measure the effect or to roll back.
  • Turning on 0-RTT for all requests.

A strong answer includes

  • Says which users benefit, namely those on lossy or distant networks and on new connections
  • Names concrete gains, including one round trip less at setup, no cross-stream blocking and connection migration
  • Lists the risks of blocked UDP, CPU cost, connection-ID routing, replay with 0-RTT and weaker debugging tools
  • Enables it at the edge only, with HTTP/2 kept as the fallback
  • Ramps by percentage and compares tail latency and errors by segment
  • Has a fast rollback by withdrawing the advertisement

Revise: HTTP/1.1 vs HTTP/2 vs HTTP/3

7. Where would you terminate TLS in this system: at the CDN, at the load balancer, or in the service itself?

Seniortlsload-balancingsecurity

What the interviewer is really testing

Whether you can connect a security decision to what each hop needs to see, state your threat model, and weigh the operational cost instead of answering "encrypt everything" or "at the load balancer" by reflex.

Show the model answer, follow-ups and checklist

Model answer

It depends on what each hop needs to read and on who I am defending against, so I will state both.

My default is to terminate at each L7 hop and re-encrypt to the next, so that nothing travels in plaintext but every proxy can do its job.

  • At the CDN. It must decrypt to cache, to apply firewall rules and to speak HTTP/3 to clients. From the CDN to my origin I use TLS again, and the CDN verifies the origin’s certificate. The origin accepts connections only from the CDN.
  • At the load balancer. It decrypts so that it can route by path, balance individual requests, retry safely and emit useful metrics. It then opens TLS connections to the services, kept in a pool so the extra handshakes are rare.
  • Between services. Mutual TLS, with short-lived certificates from an internal CA, so that each service has an identity that does not depend on its network address.

I would choose passthrough to the service only when I must: the service has to see the client’s certificate itself, the protocol is not HTTP, or a rule forbids intermediaries from seeing plaintext. The price is that the balancer becomes L4 only, with no path routing and no WAF.

I would accept plain HTTP behind the balancer only in a small system on an isolated network with nothing sensitive, and I would say so explicitly as a risk I am accepting.

Two costs to name. First, certificates on every hop mean issuance and rotation must be automated, or an expiry will take us down. Second, wherever TLS terminates, that party sees the data, and that includes a third-party CDN. For a few fields that no intermediary should ever read, such as card numbers, I would add encryption at the application level, so that the proxies only carry ciphertext for those fields.

Likely follow-ups

If the load balancer terminates TLS, how does the service learn the client IP and that the request came over HTTPS?
From headers the balancer adds, usually X-Forwarded-For and X-Forwarded-Proto, or from the PROXY protocol with an L4 balancer. The service must accept them only from the balancer, since any client can send those headers.
What do you lose with TLS passthrough?
Everything that needs the request in the clear at the balancer: routing by path, HTTP retries, a web application firewall, per-request balancing and cookie stickiness. Only the server name is visible. Each service also has to hold public certificates and pay the handshake CPU.
Security says the internal network is private, so internal encryption is unnecessary. How do you respond?
A private network is shared with every other workload and with anyone who gains a foothold on one machine, so plaintext makes lateral movement and credential theft easier. With connection pooling the cost is small. It is still a risk decision, so I would propose starting with the paths that carry credentials, payment or personal data.
How do you manage certificates for hundreds of internal services?
With an internal CA that issues short-lived certificates automatically to each workload, usually through a service mesh or a workload identity system, rotated without restarts. Nobody requests certificates by hand, and expiry is monitored on what each endpoint actually serves.

Common mistakes

  • Answering "at the load balancer" with no mention of what happens on the hop behind it.
  • Choosing passthrough and then proposing path-based routing at the same balancer.
  • Forgetting that a third-party CDN that terminates TLS sees plaintext.
  • Ignoring certificate management as a cost.

A strong answer includes

  • Links the termination point to what each hop must read (caching, routing, WAF)
  • Chooses terminate and re-encrypt as the default and says why
  • States when passthrough is right and what it costs
  • Encrypts CDN to origin and balancer to service, with certificate verification
  • Mentions mTLS or an internal CA for service identity
  • Notes field-level encryption for data intermediaries must not see

Revise: TLS

8. An expired certificate took production down for two hours. How do you make sure it cannot happen again?

Seniortlscertificatesoperations

What the interviewer is really testing

Whether you treat an outage as a systems problem with inventory, automation, independent detection and limited blast radius, and not as a human error to be fixed with a reminder.

Show the model answer, follow-ups and checklist

Model answer

“Someone forgot” is the trigger, not the cause. The cause is that renewal depended on a person remembering, and that nothing noticed until customers did. I would fix it in layers.

1. Inventory. You cannot renew what you do not know exists. List every certificate: public ones (certificate transparency logs show everything issued for our domains), internal service certificates, client certificates for partner connections, anything pinned in mobile apps, and the CA and intermediate certificates themselves, which also expire.

2. Automate issuance and renewal. Public certificates come from ACME or the cloud provider’s managed certificates. Internal ones come from an internal CA that issues short-lived certificates to workloads automatically. Renew at about two thirds of the lifetime, so a failed renewal leaves weeks or days to react, not minutes.

3. Detect independently. The renewal system cannot be trusted to report its own failure. An external probe connects to every endpoint, reads the certificate that is actually served, and alerts on days remaining: a ticket at 21 days, a page at 7. This catches the classic case where the new certificate is on disk but the process is still serving the old one.

4. Make reload safe. Servers and proxies must pick up a renewed certificate without a manual restart. Verify that as part of the renewal job.

5. Limit the blast radius. One wildcard certificate on everything means one expiry takes everything down. Use separate certificates per service or domain, so they do not all expire together.

6. Rehearse. Let a certificate expire in staging on purpose, and check that the alert fires and the automation recovers.

I would also prefer shorter lifetimes, not longer. A certificate renewed by hand once a year is renewed by someone doing it for the first time. One renewed automatically every few weeks exercises the process constantly, and a break is found while there is still time.

Likely follow-ups

The certificate had been renewed on time and the outage still happened. How?
The new certificate reached the disk or the secret store, but the server process kept serving the old one from memory because nothing told it to reload. Or the renewal reached only some instances. Checking the certificate that each endpoint really serves, from outside, catches both.
What about certificate pinning in the mobile app?
Pinning the leaf certificate means every rotation can lock out installed app versions. If you pin at all, pin a public key higher in the chain, ship a backup pin, release pins well ahead of any rotation, and keep a way to turn pinning off remotely. Many teams have dropped pinning because the outage risk outweighed the benefit.
Short-lived certificates expire more often. Why is that safer?
Because the renewal path then runs constantly, so it is automated and proven by necessity. A failure shows up within days, with the remaining lifetime as a buffer. A leaked key also stops being useful sooner, which reduces the reliance on revocation.
Which expiries do teams with good automation still miss?
The intermediate and root certificates of their own internal CA, client certificates used for mutual TLS with partners, certificates inside appliances and legacy systems, and signing certificates for single sign-on. These tend to live for years, so nobody remembers how to replace them.

Common mistakes

  • Proposing a calendar reminder or a runbook as the fix.
  • Monitoring the certificate file or the CA record, and not what the endpoint actually serves.
  • Covering public certificates only, and forgetting internal CAs and client certificates.
  • Choosing longer-lived certificates so that the problem comes round less often.

A strong answer includes

  • Builds an inventory of every certificate, including internal and client certificates
  • Automates issuance and renewal, with renewal well before expiry
  • Monitors days to expiry from outside, on the certificate being served
  • Makes sure servers reload renewed certificates
  • Limits blast radius by not sharing one certificate everywhere
  • Tests the renewal and expiry paths on purpose

Revise: TLS

9. When would you put an L4 load balancer in front of a service instead of an L7 one?

Mid-levelload-balancingl4l7

What the interviewer is really testing

Whether you know what each kind of balancer can see, and can match that to a workload, instead of treating "load balancer" as one interchangeable box.

Show the model answer, follow-ups and checklist

Model answer

For an HTTP service my default is L7, because reading the request is what lets the balancer route by path or host, balance each request separately, retry failures, terminate TLS and report per-route metrics. So the real question is when those abilities are not needed, or not possible. I would choose L4 in five cases.

  1. The protocol is not HTTP. Database connections, MQTT from devices, SMTP, a custom TCP protocol, or anything on UDP such as game traffic or DNS. An L7 HTTP proxy has nothing to parse.
  2. TLS must reach the service untouched. If the service has to see the client’s certificate itself, or policy forbids an intermediary from decrypting, the balancer can only pass the bytes through.
  3. Very high connection or packet volume. An L4 balancer does little work per packet and keeps little state, so it handles far more traffic per machine, at lower cost and latency.
  4. The client’s source address must be preserved at the network level, without relying on a forwarded header.
  5. As the first tier in front of L7 proxies. A small, fast L4 layer spreads connections over a fleet of L7 proxies, which lets the L7 tier scale out and survive the loss of an instance.

What I give up at L4 is everything that needs the request: path routing, per-request balancing, HTTP retries, header changes, a web application firewall and HTTP-level metrics. The first of those bites hardest. One HTTP/2 or gRPC connection can carry thousands of requests, and an L4 balancer sends them all to one backend.

So in a typical design I would say: L7 for the web and API traffic, L4 for the message broker and anything with long-lived raw TCP, and an L4 tier at the very front if the L7 fleet needs to scale beyond one address.

Likely follow-ups

You put gRPC services behind an L4 balancer and one backend takes most of the load. Why?
gRPC clients hold a few long-lived HTTP/2 connections and send every call down them. The L4 balancer chose a backend when each connection opened and never sees the calls inside, so a busy client pins its traffic to one server. Use an L7 proxy that balances per request, or client-side balancing.
With several L4 balancer instances, how does a connection keep reaching the same backend?
Each instance hashes the connection addresses and ports with the same consistent hashing scheme, so any of them picks the same backend for a given flow. A local connection table covers the cases where the backend set changes. This is the idea behind Maglev.
What is direct server return?
The balancer handles only inbound packets. The backend replies straight to the client, using the virtual IP as its source address. Responses are usually most of the bytes, so the balancer carries far less traffic, but it can no longer see responses or terminate TLS.
Can an L7 balancer carry WebSockets?
Yes, if it supports the HTTP upgrade. After the upgrade it relays the connection as a byte stream, so balancing is effectively per connection from then on. Its idle timeout must be raised or covered with heartbeats, and least connections is a better algorithm than round robin.

Common mistakes

  • Saying L4 is "faster" and stopping there, without the capabilities given up.
  • Claiming an L4 balancer can route by URL path or host header.
  • Forgetting that HTTP/2 and gRPC connections are long-lived, which breaks per-connection balancing.
  • Presenting it as either-or, when a common design uses an L4 tier in front of an L7 tier.

A strong answer includes

  • L4 sees addresses and ports and balances connections, while L7 parses requests and balances each one
  • L7 as the default for HTTP, with reasons
  • At least three concrete cases for L4
  • What is lost at L4, including routing, retries and per-request balancing
  • The L4 in front of L7 layering

Revise: Load balancing: L4 vs L7

10. Round robin gives every server the same number of requests, yet some servers are overloaded while others are idle. Why, and what would you change?

Seniorload-balancingalgorithmsoverload

What the interviewer is really testing

Whether you understand that equal request counts are not equal work, can list realistic causes, and can pick an algorithm for the cause you find instead of naming one from memory.

Show the model answer, follow-ups and checklist

Model answer

Round robin equalises how many requests each server is given. It knows nothing about how much work each one still has. Several things make those differ, and I would find out which applies before changing anything.

  • Request cost varies. If most requests take 10 ms and a few take 5 seconds, some servers will collect several slow ones by chance and queue everything else behind them.
  • Servers differ. Mixed instance sizes, a noisy neighbour, or one server that has just started and has cold caches. Equal shares are wrong when capacity is unequal.
  • Connections are long-lived. With HTTP/2, gRPC or WebSockets, round robin applies when the connection opens. One connection may carry a thousand times the traffic of another.
  • Affinity. Sticky sessions or hashing by client address pin heavy clients, or a whole office behind one NAT address, to a single server.

I would confirm with per-server metrics: requests in flight, CPU and p99 latency. Request counts will look perfectly even, and that is the trap.

Then the changes:

  1. Balance on outstanding work. Least connections, counted as requests in flight at L7. With several balancer instances I would use power of two choices, so they do not all pick the same server.
  2. Weights if hardware is mixed, and slow start so that a new server ramps up.
  3. Per-request balancing at L7 for multiplexed protocols.
  4. Passive outlier ejection, so a server that is failing or slow is removed quickly.
  5. A concurrency limit on each server. Past it, the server rejects quickly with a 503 and the balancer retries elsewhere. A fast rejection is better than joining a long queue.

If one endpoint causes most of the slow requests, I would also consider giving it its own pool, so that heavy reports cannot starve cheap reads.

Likely follow-ups

What is the failure mode of least connections?
A server that fails fast looks idle. It returns errors in a millisecond, always has the fewest requests in flight, and so attracts more traffic. A newly added server has the same problem in a milder form and is flooded while cold. Passive health checks that eject on errors, and slow start for new servers, cover both.
Why power of two choices and not simply the least loaded server?
With several balancers, or load figures that are slightly stale, everyone identifies the same least-loaded server and sends to it at once. Choosing two at random and taking the better one keeps most of the benefit, needs no shared state, costs constant time, and cannot stampede a single server.
You hash by customer ID for cache locality, and one customer is 30% of traffic. Now what?
That is a hot key, and no arrangement of the hash ring fixes it. Options are consistent hashing with bounded loads, where requests overflow to the next server once one exceeds a set multiple of the average, splitting that customer across several virtual keys, or giving them a dedicated pool.
How would you check that the change worked?
Compare the spread between the busiest and quietest server before and after, using in-flight requests, CPU and p99 latency per server, not request counts. Apply the change on one balancer first and watch error rates while it rolls out.

Common mistakes

  • Assuming the balancer is broken because the load is uneven.
  • Jumping to "use least connections" without asking why the work is uneven.
  • Forgetting long-lived connections, where balancing happens once per connection.
  • Ignoring what a server should do when it is overloaded anyway.

A strong answer includes

  • States that round robin equalises request counts, not work in progress
  • Gives several causes, covering varied request cost, unequal servers and long-lived connections
  • Chooses least outstanding requests or power of two choices and says why
  • Adds slow start and outlier ejection to cover the weak spots of that choice
  • Mentions per-server concurrency limits or load shedding
  • Measures by in-flight requests and tail latency per server

Revise: Load balancing: L4 vs L7

11. The load balancer marked every backend unhealthy at once and the site went down, though the servers were running. Why, and how should health checks be designed?

Staffload-balancinghealth-checkscascading-failure

What the interviewer is really testing

Whether you see health checking as a control system that can itself cause outages, and can design it to fail safely under correlated failure and overload.

Show the model answer, follow-ups and checklist

Model answer

When every server fails at the same instant, the servers are rarely the problem. The check failed for a reason they all share. I would look for one of these:

  • A deep check on a shared dependency. The health endpoint queries the database or a cache. That dependency slowed for thirty seconds, so every server reported unhealthy together.
  • Overload. The health endpoint shares a saturated thread pool with real traffic, so probes time out. The balancer removes servers, the rest take more load, and they fail too.
  • A change. A deploy moved the health path or port, or a firewall rule now blocks the balancer’s probes.

The design principles follow from that.

  1. Keep the routing check shallow. It answers one question: can this process accept and answer a request? Shared dependencies stay out. If the database is down, removing every web server helps nobody. The application should degrade instead, by serving cached data and failing only the endpoints that need the database.
  2. Separate liveness from readiness. “Restart me” and “do not send me traffic yet” are different signals. A dependency check wired to restarts will restart the whole fleet during a dependency outage.
  3. Fail open. If the healthy fraction drops below a threshold, the balancer should assume its information is wrong and send traffic to everything. Sending requests to possibly-bad servers beats sending them nowhere.
  4. Limit ejection. Passive outlier detection should remove at most a small share of the pool at a time.
  5. Do not signal overload through health checks. Shed load with fast rejections and keep the health endpoint cheap, with capacity reserved for it.
  6. Dampen. Require several consecutive failures, and add jitter to probe timing so servers are not all probed in the same instant.
  7. Treat check configuration as a risky change. Roll it out in stages.

Health checks exist to remove individual bad servers. They should never be able to remove the whole fleet.

Likely follow-ups

When is a deep health check appropriate?
When the thing it tests is specific to that instance, so that only a broken instance would fail it, such as its own disk or its own loaded configuration. Checks of shared dependencies are valuable for dashboards and alerts. They should not decide routing, unless the balancer fails open and limits how many servers it will eject.
How do health checks turn overload into a cascade?
A saturated server answers its probe late and is removed. Its traffic moves to the others, which become saturated and are removed in turn. Each removal makes the rest worse. Overload should be handled by shedding load, with the health endpoint kept cheap and given reserved capacity.
How do liveness and readiness probes differ in Kubernetes, and why does it matter here?
A failing liveness probe restarts the container. A failing readiness probe only removes it from the service endpoints. If a liveness probe checks a shared dependency, a dependency outage restarts every pod in a loop, which adds a slow, cold recovery to the original problem.
How would you test that the new design holds?
With fault injection in staging and then in production game days. Block the database and check that the healthy count stays up and the application degrades. Slow the health endpoint and check that the balancer fails open. Alert on the healthy host count falling quickly, which is rarely genuine.

Common mistakes

  • Treating it as a balancer bug and not asking what the servers had in common.
  • Making the check deeper so that it "catches more problems".
  • Wiring dependency checks to restarts.
  • Having no behaviour defined for the case where every backend looks unhealthy.
  • Using health check failure as the overload signal.

A strong answer includes

  • Identifies a correlated failure of the check, such as a shared dependency or saturation
  • Keeps the routing health check shallow and free of shared dependencies
  • Separates liveness from readiness
  • Fails open below a healthy-fraction threshold
  • Caps the share of backends that can be ejected
  • Handles overload by shedding load, with a cheap health endpoint
  • Rolls out health check changes in stages and tests them with fault injection

Revise: Load balancing: L4 vs L7

12. Design the CDN strategy for a global e-commerce site. What do you cache, for how long, and how does a price change reach users?

Seniorcdncachingpurging

What the interviewer is really testing

Whether you can classify content by how cacheable it is, choose an invalidation method for each class, and keep correctness (prices, personal data) intact while still getting a high hit ratio.

Show the model answer, follow-ups and checklist

Model answer

I would sort the content into four classes, because each needs a different policy.

1. Static assets (scripts, styles, fonts, product images). Put a content hash in the file name and cache for a year, marked immutable. A release produces new names, so these are never purged.

2. Catalogue content that is the same for everyone (product pages, category listings, the public catalogue API). Cache at the edge with a short TTL, say 60 seconds, and allow serving a stale copy while a fresh one is fetched. Tag each response with the product ids it contains. When the catalogue service changes a price, it emits an event and a small worker purges that product’s tag. The change is visible worldwide in seconds, and the TTL is the safety net if a purge is lost.

3. Personalised parts (cart count, name, recommendations). These are not cached at the edge. The page is a shared, cacheable shell, and the browser fetches the personal parts with a separate call marked private.

4. Checkout, account and all writes. These pass through uncached, though still via the edge for TLS and protection.

On price correctness: a page may show a price that is up to one TTL old. That is acceptable only because checkout always computes the price from the source of truth. A cached price is for display and is never what we charge.

Two more decisions:

  • Cache key. URL plus only what changes the response, such as currency or country. Strip tracking parameters, and do not vary on cookies or user agent, or the hit ratio collapses.
  • Origin protection. A shield tier and request collapsing so that a popular product is fetched once, stale-if-error so the catalogue survives an origin blip, and an origin that accepts traffic only from the CDN. I would never purge everything at once, because the origin is sized for the misses and not for full traffic.

I would track the hit ratio per class, since a single blended number hides a badly configured class.

Likely follow-ups

Why purge by tag and not by URL?
One product appears on many URLs: its own page, category listings, search results and API responses in several currencies. If every response is tagged with the ids of the products it contains, one purge for that tag invalidates all of them without anyone having to enumerate URLs.
A purge message is lost. What happens?
The stale object lives until its TTL expires, so the TTL is the upper bound on how long you can be wrong. That is why I keep a short TTL even with purging. Purge calls should be retried and safe to repeat, and failures should be monitored.
A flash sale changes 10,000 prices at exactly 09:00. How do you handle it?
I would not rely on a mass purge landing at one instant. Publish the sale prices ahead of time with a start time in the data, so that the page or the edge switches at 09:00 by the clock, or shorten TTLs beforehand so that objects expire around the start. The origin, behind a shield with request collapsing, must be sized for the wave of revalidation, and checkout computes the real price regardless.
How do you stop one user's page being served to another?
Personalised responses are sent with Cache-Control private or no-store, and live on paths that the CDN is configured never to cache. The edge should also refuse to cache responses that set cookies. I would add an automated test that fetches a personalised URL twice as different users through the CDN.

Common mistakes

  • Caching everything with a single TTL.
  • Purging the whole CDN on every deploy or price change.
  • Charging the customer the price shown on a cached page.
  • Caching personalised HTML at the edge.
  • Forgetting what the origin sees when the cache is cold.

A strong answer includes

  • Classifies content into static, shared dynamic, personalised and writes
  • Fingerprinted static assets with a long lifetime and no purging
  • Short TTL plus event-driven purge by tag for catalogue pages
  • Personalised parts fetched separately and never cached at the edge
  • Checkout uses the authoritative price
  • A deliberate cache key, including currency or country and excluding noise
  • Origin protection through shielding, request collapsing and serving stale

Revise: CDNs

13. We are putting an API gateway in front of 40 microservices. What would you put in it, and what would you refuse to put in it?

Seniorapi-gatewaymicroservicesauthentication

What the interviewer is really testing

Whether you have a principle for separating cross-cutting concerns from business logic, and whether you anticipate the operational and organisational risks of a component that sits in front of everything.

Show the model answer, follow-ups and checklist

Model answer

My rule is simple: the gateway gets what is the same for every service and needs no knowledge of the domain. Everything else stays in the services.

In the gateway:

  • TLS termination, so public certificates live in one place.
  • Authentication: verify the token or API key once, then pass a verified identity downstream.
  • Rate limits and quotas per client and per route, backed by a shared counter store.
  • Routing by host, path and version, including canary splits, so that services can move without clients noticing.
  • Request hygiene: size limits, schema validation at the edge of the API, CORS, compression.
  • Uniform access logs, per-route metrics and a trace id on every request.
  • Timeouts towards backends.

Not in the gateway:

  • Business rules. “Can this user refund this order?” needs the order, so it belongs to the orders service. The gateway establishes who is calling, and the service decides what they may do.
  • Client-specific aggregation, which belongs in a backend for frontend.
  • Data transformation that encodes meaning, such as price calculations or field mappings between domain models.
  • Anything that calls a database owned by a service.

The reason for being strict is what happens otherwise. Each “small exception” is reasonable, and after two years the gateway is a monolith that every team must change, that nobody fully understands, and that takes everything down when it breaks.

Then the risks I would design for from the start. First, it is on the path of every request, so I would run stateless instances across zones and treat configuration pushes, the likeliest cause of a full outage, as staged, validated and quickly reversible. Second, the gateway team must not be a bottleneck: service teams declare their own routes and limits in configuration that is checked automatically. Third, services must not trust identity headers blindly. Either only the gateway can reach them, or they verify a signed token themselves.

Likely follow-ups

A team asks to add response aggregation for the mobile home screen to the gateway. Yes or no?
No, not in the shared gateway. Composing a screen is specific to one client and changes whenever that screen changes. It belongs in a backend for frontend owned by the mobile team, or in a GraphQL layer, sitting behind the shared gateway. That keeps the gateway generic and the mobile team unblocked.
How do you enforce a rate limit across 20 gateway instances?
With counters in a shared store such as Redis, updated atomically, so that every instance sees one count per client. At very high request rates, instances can count locally and synchronise periodically, which trades some accuracy for speed. I would also decide in advance what happens when the store is unreachable. For most APIs that means allowing traffic.
Convince me the gateway is not a single point of failure.
It runs as many stateless instances across at least three zones behind a load balancer, with headroom to lose a zone. Signing keys are cached, and the only shared runtime dependency is the counter store, which fails open. Configuration is validated and released to a canary first with automatic rollback. For blast radius I would run separate gateway fleets for public, partner and internal admin traffic.
Should calls between internal services go through the gateway?
No. That would add a hop to every internal call and make the edge a dependency of the whole system. Internal calls go directly, using service discovery or a mesh with mutual TLS. The gateway is for traffic entering from outside.

Common mistakes

  • Listing features without a rule for what belongs.
  • Putting per-object authorisation or other business rules in the gateway.
  • Ignoring configuration changes as the main outage risk.
  • Keeping rate limit counters in each instance's memory.
  • Letting services trust identity headers while remaining reachable from elsewhere.

A strong answer includes

  • States the rule that the gateway holds only what is identical for every service and needs no domain knowledge
  • Includes TLS, authentication, rate limiting, routing, request limits and uniform telemetry
  • Excludes business logic, per-object authorisation and client-specific aggregation
  • Explains how verified identity reaches services, and how services are protected from direct access
  • Covers availability with stateless instances, a shared store that fails open and staged configuration
  • Addresses ownership, so that teams can change their own routes

Revise: API gateways

14. You are designing the APIs for a food delivery product with a mobile app, a restaurant web dashboard and partner integrations. REST, gRPC or GraphQL?

Seniorrestgrpcgraphql

What the interviewer is really testing

Whether you choose an API style per boundary, based on who the caller is and what the traffic looks like, and whether you can name the cost of each choice.

Show the model answer, follow-ups and checklist

Model answer

I would not pick one. There are three kinds of caller here, and I would choose per boundary.

Partners (point-of-sale vendors, aggregators): REST with JSON. Their developers use every language and expect something they can call with curl. I would publish an OpenAPI description, version in the path, and require an idempotency key on order creation. Partners also need to hear about events, and they cannot hold connections open to us, so order status changes go to them as signed, retried webhooks.

Our own apps (mobile and the restaurant dashboard): the choice is between a REST backend for frontend and GraphQL. The mobile home screen needs restaurants, promotions and the active order, from several services, in one round trip on a mobile network. The dashboard needs different fields from the same services. With two client teams whose needs diverge, I would choose GraphQL as the layer for first-party clients, and accept its costs: batching in resolvers to avoid N+1 queries, query cost limits, and persisted queries so that only known queries run. With one small team and a handful of screens, I would pick a REST backend for frontend with a few screen-shaped endpoints, because it is less machinery.

Internal services (orders, payments, dispatch, restaurants): gRPC. Typed contracts catch breaking changes at build time, deadlines propagate along the call chain, and streaming suits the feed of courier locations. It needs L7 or client-side balancing, since connections are long-lived.

One part is not request-response at all. Live order status and the courier’s position are pushed to the app over Server-Sent Events or WebSockets.

Across all three I would use cursor pagination for order history, idempotency keys on anything that creates an order or a payment, and additive changes in preference to new versions.

Likely follow-ups

Why not gRPC all the way to the mobile app?
It is a legitimate option for native apps, and some companies do it for the typed clients and compact payloads. But the web dashboard would need gRPC-Web and a translating proxy, HTTP caching is lost, debugging is harder, and partners expect REST. I would prefer one first-party style across web and mobile.
How do you make order creation safe to retry in each style?
The same way in all three: the client generates an idempotency key once per order attempt. In REST it travels in a header, in gRPC as a field in the request message, and in GraphQL as a mutation argument. The server stores the key with the result in the same transaction as the order, and returns the stored result for a repeat.
How would you version the partner API?
A version in the path, with only additive changes inside a version. A breaking change means a new version, a published deprecation window, and usage tracked per API key, so we know who still calls the old one. Pinning each partner to a dated version, as Stripe does, is a heavier alternative.
The GraphQL layer is slow for the home screen. Where do you look?
At per-field resolver timings from tracing. The usual findings are N+1 lookups that need batching, independent fields resolved one after another when they could run in parallel, one slow downstream service with no timeout, and no caching of public fields that rarely change.

Common mistakes

  • Picking one style for the whole system.
  • Choosing GraphQL or gRPC because it is modern, with no cost named.
  • Forgetting that partners need webhooks, since they cannot hold connections open.
  • Treating live order tracking as a request-response API.
  • Leaving out idempotency for order and payment creation.

A strong answer includes

  • Separate choice for partner, first-party and internal boundaries
  • REST with versioning, idempotency keys and webhooks for partners
  • GraphQL or a backend for frontend for the apps, with the deciding factor stated
  • gRPC between services, with a note on L7 balancing
  • Push channel for real-time updates
  • Cursor pagination and additive evolution
  • Costs of the chosen styles named

Revise: REST vs gRPC vs GraphQL

15. For a live order-tracking page, would you use WebSockets, Server-Sent Events or polling?

Mid-levelwebsocketsssepolling

What the interviewer is really testing

Whether you start from the direction and rate of the traffic and pick the simplest technique that meets it, instead of reaching for WebSockets whenever the word "live" appears.

Show the model answer, follow-ups and checklist

Model answer

I would start with the shape of the traffic. Updates flow from server to client: a status change a few times per order, and the courier’s position every few seconds. The client hardly sends anything. A session lasts about half an hour.

That points to Server-Sent Events. It is one-way, which is all I need. It is ordinary HTTP, so authentication with cookies, the load balancer and HTTP/2 all work as they do for the rest of the site. And the browser’s EventSource reconnects by itself and tells the server the last event id it saw, which covers the phone that goes through a tunnel.

WebSockets would work, but I would be paying for a two-way channel I do not use, and building reconnection and resume myself.

Polling deserves an honest look, because it may be enough. If positions only change every 5 seconds, polling every 5 seconds is just as fresh, and the servers stay stateless. At 100,000 active orders that is 20,000 cheap requests per second. I would choose polling for a first version or a small product, and as the fallback where streaming is blocked. SSE wins as scale grows, and because a status change such as “your order has arrived” shows instantly.

On the server, connection gateways hold the streams and subscribe to a pub/sub channel per order. The dispatch service publishes status and location events there. Each event carries an id. On reconnect, the server sends a snapshot of the current state. It does not replay old positions.

Two details. The load balancer’s idle timeout must exceed the heartbeat interval, so I send a comment line every 20 seconds or so. And in the mobile app, once it is in the background the stream is gone, so status changes also go out as push notifications.

Likely follow-ups

When would you switch to WebSockets?
When the page becomes interactive in both directions at a high rate, for example chat with the courier with typing indicators. One-way updates with the occasional client action do not justify it, because the client can send those as ordinary requests.
What about the browser limit of six connections per host with SSE?
It applies to HTTP/1.1. Over HTTP/2 or HTTP/3 each event stream is one stream on a shared connection, so serve the endpoint that way. I would also use one event stream per tab that carries every topic the page needs, not one per widget.
The phone loses signal in a tunnel for 40 seconds. What happens when it returns?
EventSource reconnects by itself and sends the id of the last event it saw. For tracking I would not replay every missed position. The server sends the current order state and the latest location, because only the newest state matters, and the client drops anything older than what it already has.
Roughly what does it take to serve 500,000 concurrent tracking pages?
Mostly idle connections cost memory. At about 20 KB each that is around 10 GB in total, so a handful of instances at 50,000 to 100,000 connections each, plus spare capacity across zones for a reconnect storm. The real work is the fan-out: one location update every 4 seconds per order is about 125,000 messages a second, and I would size on that.

Common mistakes

  • Choosing WebSockets by default without looking at traffic direction.
  • Dismissing polling without doing the arithmetic.
  • Not saying what happens when the connection drops.
  • Forgetting the backgrounded mobile app, which needs push notifications.

A strong answer includes

  • States direction, message rate and session length before choosing
  • Picks SSE for one-way updates and explains what it provides for free
  • Says honestly when polling would be enough
  • Handles reconnect by sending current state, with event ids
  • Mentions heartbeats or idle timeouts at the load balancer
  • Covers push notifications for a backgrounded app

Revise: WebSockets, SSE and long polling

16. Your chat service must hold 10 million WebSocket connections. How do you route messages, deploy without dropping everyone, and survive a gateway crash?

Staffwebsocketsscalingpub-sub

What the interviewer is really testing

Whether you can design around connection state: separating it from business logic, locating a user across a fleet, and controlling the reconnect behaviour of millions of clients during deploys and failures.

Show the model answer, follow-ups and checklist

Model answer

Shape. Two tiers. Thin connection gateways hold the sockets and do almost nothing else. Stateless chat services behind them hold the logic. At about 100,000 connections per gateway, a conservative figure that leaves memory headroom, that is roughly 100 gateways plus spares across three zones, behind an L4 load balancer with a long idle timeout.

Routing. When a client connects, its gateway writes user → gateway into a shared registry, with a TTL refreshed by heartbeats. To deliver, the chat service first persists the message to the conversation’s ordered log, then looks up the recipient’s gateways (one per device) and publishes to each gateway’s own topic. The gateway writes to the socket. If the user is offline, a push notification goes out. The live path is best effort. The log is the source of truth, and the client’s resume, “give me everything after sequence 918”, fills any gap.

Deploys. A gateway cannot be drained by waiting. It marks itself as draining so the balancer sends it no new connections, then tells its clients to reconnect, in batches over several minutes. Clients add a random delay, reconnect to another gateway and resume. I would replace a few gateways at a time. Because the gateway code is thin, it changes rarely, and most deploys touch only the stateless tier and drop nobody.

Crash. About 100,000 clients notice through a reset or missed heartbeats. Four things keep that from spreading:

  • clients reconnect with exponential backoff and jitter;
  • the fleet runs with headroom, so the survivors can absorb them;
  • each gateway limits how fast it accepts new connections;
  • resume is cheap, with one indexed read per conversation.

Stale registry entries are overwritten on reconnect or expire by TTL. Messages sent during the gap are in the log.

The principle throughout is that a connection is disposable and the log is not. If any connection can be lost at any time without losing data, then deploys, crashes and rebalancing all become the same routine event.

Likely follow-ups

A pub/sub channel per user, or a registry of user to gateway. Which, and why?
A channel per user is simpler and needs no lookup, but it means ten million subscriptions and a broker that every message crosses. A registry with one topic per gateway sends each message only where it is needed and scales better at this size, at the price of keeping the registry correct. I would start with channels in a small system and move to the registry as it grows.
How do you guarantee ordering and no loss?
Not through the live path. Each conversation has a sequence number assigned when the message is written to the durable store. Clients acknowledge what they receive, detect gaps in the sequence, and fetch what is missing. Delivery is at-least-once, and clients remove duplicates by message id.
A zone holding a third of your gateways fails. What happens next?
About 3.3 million clients reconnect. Their backoff with jitter spreads that over a minute or more, gateways cap how fast they accept connections and tell the excess to retry later, and the surviving zones must already have the capacity, because autoscaling is too slow for the first minutes. During the storm I would switch off non-essential features such as presence and typing indicators.
Why not terminate WebSockets on the chat service instances themselves?
Because every deploy of business logic would then drop connections, and a bug in that logic would crash them. The two tiers also scale on different things: connections are limited by memory, logic by CPU. Keeping the gateway thin means it changes rarely and each tier can be sized and deployed independently.

Common mistakes

  • Solving it with sticky sessions, which says nothing about reaching a user on another server.
  • Relying on the live path for delivery guarantees, with no durable log or resume.
  • Deploying gateways the same way as stateless services.
  • Ignoring the reconnect storm after a failure.
  • Quoting a 65,535 connection limit per server.

A strong answer includes

  • Thin connection gateways separate from stateless chat services
  • A sizing estimate with stated assumptions
  • A registry or pub/sub backplane to find the right gateway
  • Persist first, then deliver, with resume by sequence number
  • Gradual drain with client-side jitter for deploys
  • Headroom, admission control and backoff for crash recovery
  • Heartbeats and registry entries that expire

Revise: WebSockets, SSE and long polling