Implement a Writer-Preferring Read-Write Lock for a Photo Index

Last updated: November 29, 2026

Quick Overview

Implement a read-write lock for an in-memory Photos library index where many threads read concurrently but writers that are waiting must not be starved by a stream of new readers.

Apple
Software Engineering Fundamentals
Software Engineer
Apple
November 29, 2026
Software Engineer
Onsite
Software Engineering Fundamentals
Hard

0

0

0 solved


Implement a read-write lock for an in-memory Photos library index where many threads read concurrently but writers that are waiting must not be starved by a stream of new readers.

Photos keeps large in-memory indexes (faces, places, search tokens) that are read constantly by UI and search threads and updated occasionally by background analysis. The interviewer wants to see you reason about starvation, fairness, and invariants rather than just wrap a mutex.

What the Interviewer Expects
  • States the invariant: either any number of readers or exactly one writer
  • Identifies reader-preference starvation and fixes it by blocking new readers while a writer waits
  • Uses a single condition with predicate waits and notify_all at the right release points
  • Provides context managers so exceptions never leak a held lock
  • Discusses recursion, upgrade (read to write) deadlocks, and when os_unfair_lock or a serial queue is better
Key Topics to Cover
read-write locks
starvation
condition variables
fairness
concurrency invariants
How to Approach This
  1. Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
  2. Choose data structures based on access patterns, not familiarity.
  3. Prefer immutable data and message passing over shared mutable state for concurrency.
  4. Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
  • What happens if a reader tries to upgrade to a writer while holding the read lock?
  • How would you make this fair FIFO between readers and writers?
  • Writer preference can starve readers under constant writes: how would you bound that?
  • How does GCD's concurrent queue with barrier blocks solve the same problem?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice System Design Problems
Sample Answer
Requirements
  • Concurrent readers allowed when no writer is active or waiting.
  • Writers are exclusive.
  • A waiting writer blocks newly arriving readers (writer preference) so index updates are not starved.
  • Safe...
High-Level Design

State: active_readers, writer_active, waiting_writers, all protected by one condition variable. Readers wait until no writer is active and none is waiting. Writers register as waiting first (thi...


Submit Your Answer
Markdown supported