Real-Time Task Assignment Engine for Developer Marketplace
System DesignModel answerLast updated
Build a system that routes skill-tagged work items to qualified engineers in under 500ms while maintaining fair load distribution across 200k workers.
Context
You're building a job dispatch platform for a freelance developer marketplace. Work requests arrive continuously with skill requirements (like rust, databases, mobile-ios), and your system must route them to available engineers whose verified competencies match those requirements.
The Challenge
Design an architecture that:
- Receives work items annotated with 1–5 required skill tags from a vocabulary of 1,000 skills
- Maintains live state for engineers including their verified skills (5–30 tags each) and availability
- Routes work to qualified engineers (an engineer must possess all required tags for a work item)
- Respects capacity constraints: each engineer handles at most 2 concurrent assignments
- Operates with assignment latency under 500ms at the 99th percentile
- Distributes work fairly, avoiding both engineer overload and task starvation
Scale Parameters
- 200,000 engineers online simultaneously
- 350 work requests arriving per second at peak
- Each assignment goes through an offer phase: the engineer has 60 seconds to accept or decline
- Account for ~30% rejection rate, requiring rematching
What to Address
- Data modeling: How you represent skills, availability, and capacity; indexing approaches for rapid candidate lookup
- Matching strategy: Algorithm choice (greedy online vs. batch optimization), and how you balance speed with assignment quality
- Coordination: Preventing double-booking of work items or exceeding engineer capacity when multiple matcher instances run concurrently
- Fairness mechanisms: Ensuring varied work distribution and preventing low-priority items from indefinite waiting
- Resilience: Handling offer rejections, engineer disconnections, and component failures
Provide architectural diagrams, API contracts, and concrete algorithmic choices with their trade-offs.
Hints
Hint 1
The entire skill index can fit in memory on each matcher instance—focus your design on coordination rather than data volume
Hint 2
Batching requests for 100–200ms windows enables better global optimization than pure greedy assignment
Hint 3
Use atomic operations on capacity counters to prevent over-assignment when multiple matchers compete for the same engineer
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Real-Time Task Assignment Engine: Model Answer
1. Requirements Clarification
Start by confirming these details:
- Offer semantics: An assignment is initially an offer with a 60-second acceptance window. Capacity is reserved during this period.
- Matching rules: An engineer qualifies only if their skill set is a superset of the work item's required tags.
- Priority handling: Work items have priority levels and deadlines. The system cannot drop low-priority work indefinitely.
- Consistency: No work item can be assigned to two engineers; no engineer can exceed their capacity of 2.
Capacity calculations:
- Total system capacity: 200,000 × 2 = 400,000 slots
- Matching attempts needed: 350 arrivals/sec × 1.3 (rejection factor) ≈ 500/sec
- Presence updates: 200,000 heartbeats every 10 seconds = 20,000 writes/sec
- Index size: 1,000 tags × 25KB per bitmap (200k bits) = 25MB uncompressed; Roaring compression reduces this significantly
Key observation: The skill index easily fits in RAM. The core challenge is distributed coordination under concurrency, not data volume.
2. API Design
POST /work-items {skills[], priority, deadline, compensation}
PATCH /engineers/{id}/status {available, timezone}
POST /offers/{id}/accept {idempotency_token}
POST /offers/{id}/reject {reason}
DELETE /offers/{id} (timeout cleanup)
Offers push to engineers via WebSocket connections managed by a notification layer.
3. Data Model
Work Item:
id, required_skills (bitset), priority, deadline, state, attempt_count, excluded_engineers, optimistic_lock_version
Engineer Profile:
- Static:
verified_skills (bitset), timezone, seniority_level - Dynamic:
status, current_load (0–2), recent_volume_score, optimistic_lock_version
Offer:
id, work_item_id, engineer_id, state, expiration_time, matcher_generation
Storage choices:
- Persistent store: PostgreSQL with partitioning or CockroachDB for work items and offers
- Capacity tracking: Redis with atomic Lua scripts for real-time reservation
- Change propagation: CDC pipeline (Debezium or similar) streams engineer profile updates to matcher memory
4. System Architecture
API Gateway → Ingestion Service → Kafka (partitioned by skill cluster)
↓
Matcher Shards
(in-memory skill index + availability bitmap)
↓
Redis (capacity reservations)
↓
Assignment Database
↓
Notification Service → WebSocket → Engineers
↓
Lifecycle Manager (timeouts/rejections)
↓
Re-queue to Kafka or archive
Presence Service ← Engineer heartbeats → CDC → Matcher memory refresh
5. Candidate Selection and Matching Algorithm
Finding qualified engineers:
For a work item requiring tags {A, B, C}:
- Load bitmaps for each required skill from the in-memory index
- Intersect with the
currently_availablebitmap, starting with the rarest skill first to minimize computation - Roaring bitmap intersection completes in microseconds even with 80k-entry skill bitmaps
- Rank remaining candidates using a composite score:
- Skill level relative to work complexity
- Available capacity (prefer 0/2 over 1/2 utilization)
- Fairness penalty based on recent assignment volume
- Timezone alignment bonus
- Keep top K=30 candidates per work item
Batch matching approach (recommended):
Instead of immediate greedy assignment, collect work items into micro-batches over 200ms windows per shard:
- Model as a maximum flow problem: source → work items (capacity 1) → engineers (capacity = 2 - current_load) → sink
- With ~150 items per batch and K=30 candidates each, the graph has ~4,500 edges
- Hopcroft-Karp runs in O(E√V) ≈ 3–5ms for this scale
- Alternatively, use min-cost max-flow where costs incorporate priority and fairness scores
Why batching wins:
- Better global optimization: Avoids greedy mistakes where scarce specialists get assigned to common work
- Still meets latency: 200ms window + 5ms solve + 15ms commit + 50ms push = 270ms end-to-end
- Adaptive windowing: Shrink to 50ms under low load; flush early when approaching an SLA deadline
Fairness mechanisms:
- Work-side fairness: Priority = base_priority + age_penalty + deadline_urgency. Use weighted round-robin across priority classes within each batch.
- Engineer-side fairness: The
recent_volume_score(exponentially weighted moving average of assignments) penalizes overloaded engineers in ranking, spreading work naturally.
6. Distributed Coordination
Partitioning strategy:
- Offline, cluster the 1,000 skills into ~64 groups based on co-occurrence patterns (community detection on the skill graph)
- Route each work item to the Kafka partition corresponding to its rarest skill's cluster
- Each matcher shard owns one partition, ensuring similar work competes in the same batch
- Replicate the full engineer index (25MB) to every shard—small enough for full replication
Engineers with diverse skills appear in multiple shards' candidate sets. This creates the cross-partition coordination challenge.
Preventing double-assignment:
Phase 1: Work item uniqueness via partition ownership
- Each Kafka partition has exactly one active consumer (matcher) holding a lease with a monotonic generation number
- Assignment records include this generation; the database rejects writes from stale generations
- Kafka's consumer group protocol ensures only one active owner per partition
Phase 2: Engineer capacity via atomic reservation
-
After the batch solver proposes assignments, execute a reservation phase:
-- Redis Lua script (atomic on single engineer key) if engineer.active + engineer.reserved < 2 and engineer.available then engineer.reserved = engineer.reserved + 1 return "SUCCESS" else return "CONFLICT" end -
This single-key atomic operation prevents capacity violations even when multiple shards target the same engineer simultaneously
-
Process reservations in scarcity order: commit rare-skill matches first to minimize conflicts
Conflict resolution:
- On reservation failure, add that engineer to the work item's exclusion list and requeue to the next batch window
- Because of skill clustering, cross-partition contention is rare (<5% of attempts)
7. Handling Failures and Churn
Offer lifecycle:
- Acceptance: Move reserved capacity to active; work begins
- Rejection: Release reservation immediately; requeue work item with that engineer excluded
- Timeout: A background sweeper checks
expiration_timeevery 10 seconds, releases capacity, and requeues work
Engineer disconnection:
- Heartbeat timeout (30 seconds) marks engineer unavailable and releases their reservations
- Active work continues; engineers reconnect to resume
Matcher failure:
- Kafka consumer rebalancing assigns the partition to another instance
- The new instance rejects writes with old generation numbers
- In-flight offers either complete or timeout naturally; the sweeper handles cleanup
Database unavailability:
- Matchers buffer failed writes with exponential backoff
- Work items remain in Kafka until successfully committed
- Idempotency tokens prevent duplicate offers after retries
8. Monitoring and Tuning
Key metrics:
- Assignment latency (p50, p95, p99)
- Match rate and first-attempt success percentage
- Engineer utilization distribution (detect overload/underload)
- Work item wait time by priority class
- Reservation conflict rate per shard
Tuning levers:
- Batch window size (50–300ms)
- Candidate set size K (trade quality for speed)
- Fairness weight in scoring
- Partition count (rebalance skill clusters as the catalog evolves)
9. Follow-Up Considerations
Priority inversion: What if high-priority work gets blocked behind batch processing of low-priority items? Response: Implement priority lanes with dedicated partition capacity or early-flush logic.
Geographic distribution: How would you handle engineers and work distributed globally across regions? Response: Regional shards with overflow routing; preference for same-region matching to reduce latency and support timezone alignment.
Skill deprecation and evolution: The skill vocabulary changes over time. How do you handle migrations? Response: Versioned skill taxonomies with mapping layers; gradual migration of engineer profiles; backward-compatible matching during transition periods.
This design delivers sub-500ms assignment latency, fair load distribution, and strong consistency guarantees while scaling to hundreds of thousands of concurrent participants.