Design a Distributed Crossword Fill Engine
System DesignModel answerLast updated
Architect a scalable, fault-tolerant distributed system to solve large constraint-satisfaction crossword grid fills using parallel search strategies.
Design a distributed system that solves $N \times N$ crossword puzzle fills given an input grid pattern (with black cells and optional pre-filled letters) and a large lexicon of valid words.
The system should explore the combinatorial search space efficiently, distributing work across a cluster of compute nodes while guaranteeing quick termination upon discovering a valid fill or proving that no valid fill exists.
System Requirements
Functional Requirements
- Accept grid definitions ($N \times N$, up to $20 \times 20$) and target lexicon identifiers or custom word lists.
- Perform constraint-satisfaction exploration to find a complete, valid grid assignment or return
UNSATISFIABLE. - Support asynchronous job submission, execution monitoring, and cancellation.
Non-Functional Requirements
- Scalability: Handle grid sizes up to $20 \times 20$ (~150 intersecting word slots) and dictionaries containing over 500,000 words.
- Low Latency & High Throughput: Minimize search time by eliminating remote network calls inside tight inner solver loops.
- Fault Tolerance: If any compute node crashes while processing a branch of the search tree, no work should be lost permanently and no duplicate invalid work should corrupt the result.
- Resource Limits: Gracefully handle unsolvable or overly complex puzzles via configurable time and compute budgets.
Hints
Hint 1
Consider how the dictionary is queried. Is a remote database lookup feasible inside a backtracking loop exploring millions of states per second?
Hint 2
How can you represent subproblems concisely so that nodes do not need to ship full grid states across the network?
Hint 3
What mechanism ensures work remains balanced when some branches terminate in milliseconds while others take hours?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. System Requirements & System Limits
Scale & Performance Expectations
- Grid Bounds: $N \le 20$. A $20 \times 20$ grid contains up to 400 cells, producing roughly 120–160 "slots" (contiguous runs of length $\ge 2$ across or down).
- Lexicon Size: 500,000 words. Average word length $\approx 6 \text{--} 8$ characters. Uncompressed text is roughly 4–5 MB. With positional indexing structures, the full in-memory lookup index spans roughly 150–300 MB.
- Inner Loop Requirements: A single node can explore $10^5 \text{--} 10^7$ candidate branches per second if memory lookups are local. Any remote network call (e.g., Redis/DB lookup) in the inner loop adds $1 \text{ ms}$, dropping performance to 1,000 checks/sec (a $10,000\times$ degradation).
Core Architectural Principle
Zero-Network Inner Loops: The dictionary MUST be fully replicated in RAM on every worker node as an immutable index. Workers must perform constraint propagation and variable assignment using local memory only.
2. Interface & API Design
The API allows clients to register dictionaries, submit grid problems, check execution state, and fetch completed fills.
POST /v1/dictionaries
Payload: { name: string, words: string[] }
Response: 201 Created { dictionary_id: "dict_sha256_hash" }
POST /v1/jobs
Payload: {
grid: string[], // e.g. ["C.T#", "....", "#...", "...."] where '.' is empty, '#' is block
dictionary_id: string,
timeout_seconds: number,
max_cpu_hours: number
}
Response: 202 Accepted { job_id: "job_uuid" }
GET /v1/jobs/{job_id}
Response: 200 OK {
status: "QUEUED" | "RUNNING" | "SOLVED" | "UNSATISFIABLE" | "TIMEOUT",
solution: string[] | null,
metrics: { nodes_explored: 1420500, active_workers: 8, elapsed_ms: 1240 }
}
DELETE /v1/jobs/{job_id}
Response: 200 OK { status: "CANCELLED" }
3. Data Representation & Local Constraint Solver
Indexing the Lexicon (Bitset Positional Index)
Instead of standard tries (which excel at prefix lookups but perform poorly for wildcard constraints like ?A?T?), the dictionary is stored using positional bitsets.
- Partition words by length $L$.
- Assign each word of length $L$ a unique integer index $0 \le i < K_L$.
- Maintain a positional bitset array:
BitSet[Length][Position][Character]. - To find all words of length 5 matching pattern
?A?T?: $$\text{ValidCandidates} = \text{BitSet}[5][1]['A'] \ & \ \text{BitSet}[5][3]['T']$$
Evaluating slot intersections becomes a series of fast bitwise AND operations, allowing millions of word matches per second per core.
BitSet[5][1]['A'] : 1 0 1 1 0 0 1 ...
AND BitSet[5][3]['T'] : 0 0 1 1 0 1 0 ...
-----------------------------------------
Result Candidates : 0 0 1 1 0 0 0 ... (Word IDs #2 and #3 match)
Constraint Satisfaction Problem (CSP) Formulation
- Variables: Each horizontal and vertical slot $S_1, S_2, \dots, S_m$.
- Domains: Valid words from the dictionary of matching length that satisfy initial pre-filled letters.
- Constraints: Overlapping cells between intersecting slots must match.
- Search Strategy: Depth-First Search (DFS) with:
- Minimum Remaining Values (MRV): Select the slot with the smallest remaining candidate domain.
- Arc Consistency / Forward Checking (AC-3): Prune domains of intersecting slots immediately when a word is placed. If any domain reduces to size 0, backtrack immediately.
4. Distributed System Architecture
+------------------------+
| Client / UI |
+-----------+------------+
| REST
+-----------v------------+
| API Gateway |
+-----------+------------+
|
+-----------v------------+
| Job Manager |
+---+----------------+---+
| |
Tasks Queue | | Status updates
v v
+----+----------------+----+
| Central State Store / DB |
| (PostgreSQL / Redis KV) |
+----+----------------+----+
| |
Poll / | | Heartbeat &
Lease v v Splits
+-----+----------------+-----+
| Worker Pool |
| [Node 1] [Node 2] [Node 3|
| (Each has dict pre-loaded) |
+----------------------------+
Component Roles
-
Job Manager:
- Accepts job requests, validates grid layouts, and extracts variable slots.
- Runs an initial local AC-3 pass. If the grid is trivially invalid or immediately solved, returns early without allocating cluster resources.
- Expands the root node into an initial pool of task subtrees (e.g., assigning the top 2–3 MRV slots) and seeds the work queue.
-
Distributed Work Queue & State Store:
- Stores task definitions, task statuses (
PENDING,LEASED,COMPLETED), and execution metrics. - Uses Redis or PostgreSQL for atomic operations and leasing mechanisms.
- Stores task definitions, task statuses (
-
Worker Nodes:
- Cache dictionary indexes locally in memory (loaded on initialization from shared object storage like S3).
- Lease execution tasks containing a sequence of initial assignments.
- Execute local depth-first backtracking with search budgets.
5. Work Partitioning & Dynamic Load Balancing
Task State Representation
A task is represented strictly by a small array of initial assignments:
Task = [ (Slot_0, WordID_42), (Slot_3, WordID_1091), ... ]
Workers re-apply these decisions locally and continue search from that point. Key Benefit: Tasks are tiny (~1 KB), immutable, and stateless. No complex grid states are transmitted across nodes.
Dynamic Work-Stealing / Budgeted Splitting
Static splitting (e.g., dividing the root domain equally into $N$ tasks) fails because constraint spaces are unpredictable: one subtree might hit a dead end in 2 milliseconds while another takes 3 hours.
Worker processing subtree task:
[Slot 0 = WORD_A]
|
+--> [Slot 1 = WORD_B] (Actively searching deep tree...)
|
+--> [Slot 1 = WORD_C] \
+--> [Slot 1 = WORD_D] +-- Untried branches donated back
+--> [Slot 1 = WORD_E] / to queue when budget expires!
Execution Protocol:
- A worker leases a task with an allocated node-exploration budget (e.g., $1,000,000$ state evaluations or 2 seconds).
- If the worker finds a solution: It updates the job state to
SOLVED, posts the result, and broadcasts a broadcast cancellation. - If the worker explores the entire subtree within the budget: It marks the task
COMPLETED_EXHAUSTED. - If the budget expires before exhaustion: The worker splits its remaining untried search space at shallow stack depths, enqueues these shallow branches as new child tasks, and updates its own task status to
COMPLETED_SPLIT.
6. Edge Cases & Fault Tolerance
Node Failure Handling
- Tasks are leased with a short lease TTL (e.g., 10 seconds) and periodically renewed via worker heartbeats.
- If a worker node crashes or loses connection, its lease expires. The control plane transitions the task state back to
PENDINGfor another worker to claim. - Because subproblems are identified deterministically by initial decision branches, re-executing a task is completely idempotent.
Early Termination & Broadcast Cancellation
- Solution Found: When any worker finds a valid grid configuration, it executes a compare-and-swap (CAS) update on the Job state:
RUNNING -> SOLVED. - Upon successful CAS, the worker issues a Redis Pub/Sub message:
CANCEL_JOB <job_id>. - All active workers check a thread-safe local cancellation flag every $10,000$ iterations and abort immediately upon receiving the signal.
Proving Unsolvability (UNSAT)
- A job is declared
UNSATISFIABLEif and only if:- The task queue contains zero
PENDINGorLEASEDtasks. - Total root splits have finished without finding a match.
- No task terminated with error/timeout.
- The task queue contains zero
- Tracked via standard parent-child task counters in the DB state store.
7. Operational Trade-Offs
| Approach / Choice | Pros | Cons |
|---|---|---|
| Replicated In-Memory Dictionary | Eliminates network bottlenecks; ultra-fast local lookups. | Requires RAM footprint (~300MB) on every worker node. |
| Bitset Intersection Indexing | Instant candidate matching for arbitrary wildcard slots (?A?T?). | Higher index generation time during initial lexicon load. |
| Decision-Path Task Encoding | Task payloads are tiny (~1 KB), completely idempotent, easy to replay. | Minimal redundant re-computation of initial assignments on startup. |
| Dynamic Budgeted Splitting | Self-balancing load across non-uniform, unpredictable search trees. | Slight overhead in coordination storage when writing split subtrees. |