Building a Crew Rostering Backend with Safe Shift Claiming
System DesignModel answerLast updated
Design a backend for posting, claiming, and locking restaurant work shifts that prevents double-claims and overlapping assignments while serving a heavily read schedule view.
Crew rostering service for restaurants
You are asked to design the backend of a staff-rostering product used by restaurant chains. Managers publish work shifts for their location, and staff members pick up the shifts they want. Once a manager is happy with a week, they can freeze it.
What the system must do
- A manager can add, change, and remove shifts for one of their locations.
- A staff member can browse the shifts still open and ask to take one.
- No staff member may hold two shifts whose time ranges overlap.
- A manager can finalize a schedule. After that, staff can no longer change anything on it.
Quality targets
- Claiming must be strongly consistent: a slot can never end up with more people than it has capacity for.
- The workload is dominated by reads, since staff check their schedule many times a day.
- Scale: 10,000 restaurants, each with up to 200 staff.
What to deliver
- Data model: the main entities and how they relate.
- API: endpoints to create a shift, list open shifts, and claim a shift, including meaningful error codes.
- Concurrency: how you guarantee correctness when many people try to claim the same shift at the same moment, and how finalization interacts with in-flight claims.
- Read scaling: how you would cache the schedule and keep it reasonably fresh.
State your assumptions and discuss the trade-offs of your choices.
Hints
Hint 1
Start with clarifying questions: can a shift have several slots, can people work at more than one location, and is a claim instant or subject to approval? Then do a quick estimate to see whether volume or contention is the real difficulty.
Hint 2
Push the invariants into the database: a conditional update on a counter for capacity, and an exclusion or unique constraint for overlapping time ranges. Avoid read-then-write logic in application code.
Hint 3
Treat reads and writes differently: the cached schedule can be slightly stale, but the claim path must always validate against the primary database. Think about how finalize and claims coordinate through a row lock on the schedule.
Hint 4
For caching, consider cache-aside with a version number, invalidation driven by committed changes (outbox/CDC) rather than dual writes, ETags, and push notifications to cut polling.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The core of this problem is correctness under concurrency: no over-filled shifts, no overlapping assignments, no changes after finalization. Once that is solid, the read-heavy schedule view can be handled with a cache on top. Decide the consistency story first, then layer caching over it.
1. Requirements and sizing
Clarifying questions, with the assumptions I would state:
- Multiple slots per shift? Yes, a
headcountfield (e.g., "3 servers, 5pm to 11pm"). - Multiple locations per employee? Yes, so overlap checks are per employee across all locations.
- Instant claim or manager approval? Support both via a
requires_approvalflag. The race logic is identical.
Rough numbers:
- Employees: 10,000 x 200 = about 2M.
- Shift slots: roughly 1,000 per restaurant per week, so about 10M per week and about 500M per year. Comfortable for partitioned Postgres.
- Reads: 2M users x ~10 views per day is about 20M per day, around 230 QPS on average and perhaps 3-5k QPS at peaks (schedule publication, start of shifts).
- Writes: low on average but bursty. When a manager posts open shifts, dozens of people hit the same rows within seconds.
Conclusion: storage is not the issue. Hot-row contention and read fan-out are.
2. Data model
I choose a relational store (Postgres) because claiming needs transactions and declarative constraints. A cache gives us the read scale that NoSQL would otherwise offer.
restaurant(id, org_id, name, timezone)
employee(id, org_id, name, ...)
employment(employee_id, restaurant_id, role)
schedule(id, restaurant_id, week_start, status[DRAFT|PUBLISHED|LOCKED], version)
shift(id, schedule_id, restaurant_id, role, start_at, end_at,
headcount, filled_count, status[OPEN|FULL|CANCELLED], version)
assignment(id, shift_id, employee_id, start_at, end_at,
status[ACTIVE|RELEASED], source[CLAIM|ASSIGN], created_at)
The assignment row denormalizes the shift's times so a constraint can use them directly. Two constraints carry the correctness:
CREATE EXTENSION btree_gist;
ALTER TABLE assignment ADD CONSTRAINT no_overlap
EXCLUDE USING gist (employee_id WITH =, tstzrange(start_at, end_at) WITH &&)
WHERE (status = 'ACTIVE');
CREATE UNIQUE INDEX one_per_shift ON assignment(shift_id, employee_id)
WHERE status = 'ACTIVE';
Store times in UTC and use the restaurant timezone only for display. Partition shift and assignment by month on start_at, and index shift(restaurant_id, start_at) and assignment(employee_id, start_at).
3. API
POST /restaurants/{rid}/shifts create shift -> 201
PATCH /shifts/{id} edit (If-Match: version) -> 200 | 409 | 423
DELETE /shifts/{id}
GET /restaurants/{rid}/shifts?from=&to=&status=OPEN&role= (ETag)
GET /employees/{eid}/assignments?from=&to=
POST /shifts/{id}/claims (Idempotency-Key header) -> 201 | 409 | 423
DELETE /assignments/{id} release or manager unassign
POST /schedules/{id}/finalize -> 200
Status codes are part of the contract: 409 for "shift full" or "overlaps another shift", 423 for "schedule locked". An idempotency key makes retries on unreliable restaurant networks safe.
4. Concurrency strategy
A claim runs as one transaction:
BEGIN;
SELECT status FROM schedule WHERE id = :sid FOR SHARE; -- 423 if LOCKED
UPDATE shift
SET filled_count = filled_count + 1,
status = CASE WHEN filled_count + 1 = headcount THEN 'FULL' ELSE 'OPEN' END,
version = version + 1
WHERE id = :shift_id AND status = 'OPEN' AND filled_count < headcount;
-- 0 rows updated -> ROLLBACK, 409 "shift full"
INSERT INTO assignment(shift_id, employee_id, start_at, end_at, status, source)
VALUES (...);
-- exclusion violation -> ROLLBACK, 409 "overlaps existing shift"
COMMIT;
Why it is correct:
- The conditional UPDATE serializes claimers. It takes a row lock; competing claimers wait, then re-evaluate the
WHEREclause after the earlier one commits. Exactlyheadcountsucceed, the rest update zero rows. - No check-then-act gap. There is no separate read before the write, so nothing can slip in between.
- Overlaps are enforced by the database. The exclusion constraint covers claims and manager assignments alike, across locations. Application-level checks cannot guarantee this under concurrency.
- Finalize cannot interleave. Finalize takes
FOR UPDATEon the schedule row and setsLOCKED. Claims holdFOR SHARE, so each claim either commits before the lock or seesLOCKEDand returns 423.
Optimistic vs pessimistic:
- Manager edits are low-contention, long read-edit-save flows, so use a version column with
If-Match. - For claims, the single-statement conditional update is effectively a compare-and-set. It avoids the retry storms a read-version-then-write loop would cause on a hot shift.
- I would not add distributed Redis locks. The database is already the source of truth and provides the locking.
5. Read scalability
- Cache-aside in Redis keyed
sched:{restaurant_id}:{week_start}, holding the rendered schedule plus its version. Working set: 10k restaurants x 2-3 active weeks x ~100 KB is a few GB. - Invalidate from committed changes. Each write bumps
schedule.versionand writes an outbox row; a CDC consumer (e.g., Debezium and Kafka) deletes or rebuilds the key. This avoids the dual-write bug where the database commits but the cache update is lost. Add a TTL (about 10 minutes) as a safety net. - ETags let clients send
If-None-Matchand receive304for unchanged schedules. - Push over poll: WebSocket or mobile push on schedule change cuts polling traffic.
- Eventually consistent reads, strongly consistent writes. A cached "OPEN" shift may be briefly stale, but the claim always validates against the primary. This is the key trade-off.
- Read replicas serve cache misses and history queries.
- Sharding is not needed at this scale; a single primary with partitions suffices. If it grew, shard by
org_idorrestaurant_id. The cross-location overlap constraint is the reason to keep an employee's assignments co-located, so shard by organization rather than by restaurant.
6. Common mistakes
- Checking availability or overlap in application code before inserting (a classic race).
- Using the cache to decide whether a claim can succeed.
- Forgetting the interaction between finalize and in-flight claims.
- Local-time storage, leading to daylight-saving bugs on overnight shifts.
- Not making claim requests idempotent.
- Reaching for distributed locks when a row lock already exists.
7. Likely follow-ups
- Manager approval flow: add a
PENDINGassignment status that holds a slot, and use the same conditional update. - Waitlists: a queue per full shift, promoted on release.
- Shift swaps: release and claim in a single transaction.
- Weekly hour caps and labor rules: enforce in the transaction with a per-employee weekly counter or a check query under an employee-row lock.