The interview problem

Practice prompt

Twenty API instances submit report-generation jobs to a shared execution service. That service may run at most 100 jobs concurrently. Design a distributed semaphore with retries, client crashes and a fair waiting queue. Explain what happens when a permit expires while its job is still running.

Original system-design practice, not a reported company interview. Counts and timing are hypothetical. Official technical references retrieved September 27, 2026.

1. Define what the limit protects

A rate limiter bounds arrivals over time; a semaphore bounds simultaneous ownership. The requested invariant is stronger than “at most 100 unexpired tokens”: at most 100 jobs may actually execute. Decide whether a job occupies a slot while queued inside the executor, starting, running or canceling. Here all admitted nonterminal jobs reserve a slot, including uncertain starts and cancellation in progress.

Assume every execution request passes through an authoritative admission service integrated with the executor. API instances cannot bypass it. If an external vendor cannot expose admission, terminal status or effective cancellation, a strict cap may require holding uncertain slots indefinitely. Client timeouts alone cannot establish that remote work stopped.

2. Put accounting beside execution admission

API instances → durable fair queue → admission coordinator → execution service
                         ↕                  ↕                       ↕
                   request IDs       100 slot records          job status by ID
                   deadlines         generation + job ID      terminal evidence

Use a linearizable transactional store or consensus state machine for slot ownership and queue admission. A slot record contains slot ID, generation, request ID, job ID, state and owner metadata. Keep a unique request record so an acquire retry returns the existing reservation or terminal outcome instead of consuming another slot.

Possible states are FREE, RESERVED, STARTING, RUNNING, CANCELING and TERMINAL. FREE to RESERVED assigns a new generation and request atomically. Terminal completion releases the capacity only after a durable transition matching the current slot generation and job ID. Duplicate completion events are harmless; an old completion cannot free a slot occupied by a newer job.

Physical execution must also be idempotent by job ID. The executor atomically validates the admitted generation and records acceptance before scheduling that job. It must reject revoked reservations and duplicate starts. This is an explicit executor contract, not a property supplied by a lease library alone.

3. Serialize start against revocation

Suppose slot 8 generation 41 is reserved for job J. A client pauses before sending start. A cleanup process wants to reclaim the reservation. If start and revoke consult separate stale caches, cleanup can free the slot while the delayed request starts J.

Instead, start acceptance and reservation revocation meet at the same authoritative execution-admission boundary. If revocation wins, later starts for generation 41 are rejected. Persist that rejection as a tombstone or generation high-water mark before acknowledging revocation; the coordinator can recycle the slot only after this acknowledgment or equally authoritative terminal evidence. If start wins, the slot is occupied until J is known terminal. A frontend lease may mark its owner unreachable, but it cannot change RUNNING to FREE.

A network timeout after start has an unknown outcome. Query by J or retry the identical start request under executor deduplication. A new random job ID would create a second execution. If coordinator and executor are separate services, model their interaction as a durable protocol: retain the slot through uncertain messages and reconcile after recovery rather than pretending two database writes are atomic.

4. Show why expiry alone oversubscribes

At time zero, 100 jobs begin with 30-second client leases. They each take 120 seconds. Their clients stop renewing, but the executor continues. At 30 seconds, an unsafe semaphore deletes the leases and admits another 100 jobs. Actual concurrency is now 200 despite only 100 current tokens.

If it repeats at 60 and 90 seconds, there can be 400 running jobs immediately before the first wave finishes. With these aligned waves, instantaneous starts, constant 120-second runtime and a 30-second recycle interval, four waves overlap. This is an illustrative bound under stated timing, not a universal four-times bound. Arbitrarily long work or repeated premature recycling can produce arbitrarily larger oversubscription.

The strict design marks unreachable ownership as suspect and consults the executor. It retains occupied slots while jobs continue. Cancellation is a request, not terminal evidence; release follows confirmed termination. If status is unavailable, preserve safety by withholding new admission for those slots and expose the resulting loss of capacity.

5. Make fairness and retries explicit

Order waiting requests using a committed sequence. For equal-weight jobs, admit from the head when capacity becomes free. Queue insertion retries use a stable request ID. Waiting clients may watch a predecessor or receive targeted notifications to avoid waking every waiter for one free slot. Notifications are hints; admission must recheck authoritative state.

A deadline expiring in the waiting state can remove the request without touching execution capacity. A deadline after reservation requires the start-versus-revoke protocol. If the deadline races with accepted execution, cancel the job through its lifecycle rather than assuming it never started. Bound queue length and return overload responses before retaining unbounded work.

Weighted jobs complicate fairness. A job needing ten units must acquire all ten atomically; partial acquisition can deadlock. Strict FIFO may leave capacity idle behind a large head request. Allowing smaller jobs to bypass it improves utilization but risks starvation, so specify an aging rule or a bounded bypass policy and measure wait time by tenant.

6. Calculate useful throughput and queue growth

With 100 slots and mean service time of 20 seconds, a saturated ideal system completes about 100/20 = 5 jobs/second. At four admitted arrivals/second and a stable mean service time, average running work is approximately 4 × 20 = 80 jobs. This is a steady-state average, not a guarantee against bursts or long-tail runtimes.

At six arrivals/second with capacity remaining five completions/second, backlog grows by one job/second, or 3,600 jobs/hour. A semaphore prevents excess execution but does not solve demand exceeding capacity. Set admission deadlines and upstream backpressure based on the waiting-time objective.

If 15 slots have uncertain running jobs during an outage, the remaining 85 slots support at most approximately 4.25 jobs/second at the same mean runtime. This is a visible availability cost of retaining uncertain ownership. Automatically reclaiming those 15 slots would conceal the uncertainty instead of resolving it.

7. Recover without forgetting work

After coordinator leadership changes, recover committed slot records and reconcile STARTING, RUNNING and CANCELING states by stable job ID. Executor terminal history must outlive retry and reconciliation windows. Retiring detailed history also requires rejecting old request generations, so a very late retry cannot restart a forgotten job. A missing status record does not prove nonexecution unless the executor's retention and lookup contract says so.

Fencing old coordinators prevents new admission from stale leaders, but does not terminate jobs they already admitted. Keep those jobs in the accounting. During a control-store partition, permit already admitted work to finish if safe, but do not grant new capacity without authoritative admission.

Lowering the configured cap from 100 to 60 while 90 jobs run does not instantly achieve 60. Enter a drain policy: admit none until occupancy falls below the new limit, or explicitly cancel selected jobs and wait for termination. Increasing a limit is an operational capacity decision; first verify the executor can sustain it.

Audit slot occupancy against executor inventory, request-ID duplicates, unknown-start age, cancellation age, queue wait and terminal-event lag. Test delayed starts after revocation, duplicate release, leader failover after acceptance, stuck cancellation and reduced limits. A healthy lease heartbeat is not evidence that the concurrency invariant holds.

8. Follow-ups and self-review

Follow-ups: Can a fencing token alone stop existing CPU work? No; it can reject future operations at a cooperating boundary, while admitted work still needs lifecycle accounting. Can a client release immediately after timeout? Not safely when execution outcome is unknown. Does FIFO guarantee equal customer share? No; one tenant can enqueue many jobs, so tenant fairness may require a separate scheduler. What if a job never terminates? Hold its capacity or use an executor-enforced termination mechanism; do not silently redefine the limit.

Score 0–2 each for the physical concurrency invariant, atomic/idempotent admission, handling expired owners, queue fairness and backpressure, and recovery from uncertain starts. A strong answer distinguishes token ownership from running work throughout.

Sources and next steps

The executor protocol, expiry counterexample and workload arithmetic are original. These references do not imply that a coordination library terminates external jobs. Continue with distributed locks and fencing.

Continue your preparation

Choose a connected learning path or browse more System design questions. Read our editorial method and attribution policy.