Concurrency
183 bites tagged Concurrency — interview questions with model answers, and 60-second explainers.
Concurrent TCP server: Go goroutines vs Rust std::thread
Both accept in a loop; Go spawns a goroutine per connection (go handle(conn)); Rust spawns an OS thread (thread::spawn moving the stream). stdlib networking and concurrency.
Rust async/await vs Go goroutines
Go schedules goroutines on a built-in runtime transparently; Rust futures are inert until polled by an external runtime like Tokio, and async colors functions. async execution models.
Sharing mutable state: Go mutex vs Rust Arc Mutex
Go uses sync.Mutex by convention; Rust wraps data in Arc<Mutex<T>> so locking is mandatory, enforced by Send/Sync and the borrow checker. shared-state concurrency and compile-time safety.
Rust borrow rules versus Go race prevention
Rust's aliasing-XOR-mutability rule plus Send and Sync make races a compile error; Go prevents them at runtime via channels, mutexes and the race detector. how each language stops data races.
Which Web API offloads expensive work from the main UI thread?
Cite Web Workers, instantiate new Worker(url), and communicate via postMessage and onmessage. knowledge of moving CPU-heavy work off the main thread. citing setTimeout or async/await, which still run on the main thread.
Explain IndexedDB transactions and readonly vs readwrite modes
Every operation needs a transaction; readonly allows concurrent readers, readwrite is exclusive; they auto-commit when idle. Understanding of IndexedDB's transactional model and concurrency.
Offload CPU-intensive work to a Web Worker and explain communication.
This tests main-thread blocking and worker messaging. A strong answer covers: new Worker(url), moving logic to a worker file, sending data via postMessage(), and receiving results via onmessage. A red flag is suggesting DOM use or shared memory from workers.
Why did React replace the Stack Reconciler with Fiber?
Tests React scheduling limits. Good answers note the old reconciler was synchronous and recursive, blocking the main thread, while Fiber enables incremental rendering and interruptible work. Red flag: citing Hooks or vague speed claims without frame budgets.
Why are contextvars better than threading.local in async Python?
This tests whether you know async tasks share OS threads, making thread-local storage unsafe for request state. A great answer notes ContextVar is task-local and resets automatically, while threading.local bleeds across concurrent coroutines.
How do you gracefully cancel and clean up an asyncio task?
This tests asyncio cooperative cancellation and cleanup. A strong answer covers catching CancelledError at await points, using try/finally or async context managers for cleanup, and re-raising.
Unhandled exception in asyncio.create_task(): consequence and detection
Tests Task exception capture vs propagation. Good answer: exceptions are stored in the Task object, the loop keeps running, and the creator must await the task or call task.exception() to retrieve it; unretrieved ones may be logged.
When should you use asyncio.Lock over threading.Lock?
This tests cooperative multitasking knowledge: asyncio.Lock yields to the event loop via await, while threading.Lock blocks the OS thread and freezes the loop. A red flag is claiming threading.Lock works because locks are universal.
Explain the asyncio event loop and cooperative multitasking
Tests if you view the event loop as a single-threaded orchestrator, not magic parallelism. Strong answers note it runs tasks and callbacks, manages a ready queue, and yields control at await. Red flag: calling it multithreading or parallel execution.
How do you safely execute blocking code from an async function
Tests whether you know how to prevent event loop blocking by offloading sync work. Name asyncio.to_thread or run_in_executor, explain ThreadPoolExecutor scheduling, and note when processes beat threads.
Explain await's purpose, awaitable types, and event loop signaling
This tests whether you understand await as a yield point. A strong answer lists three awaitables (coroutines, Tasks, Futures), explains await yields control to the event loop until completion, and warns that a bare coroutine call does not run it.
How does Uvicorn use asyncio to handle thousands of concurrent connections?
Tests async concurrency and the GIL. Great answers cover the event loop suspending coroutines at await, Uvicorn interleaving connections, and multi-process workers for parallelism. Red flag: claiming asyncio uses threads per request or bypasses the GIL.
How do you structure concurrent API calls with asyncio.gather in FastAPI?
Tests FastAPI async concurrency. Strong answer: async def endpoint with two async HTTP requests in asyncio.gather, cutting total latency from sum to max of the two. Red flag: using sync clients or threads instead of async I/O.
What is the difference between def and async def in Python and FastAPI?
Tests event-loop boundaries: async def yields control via await for non-blocking I/O, def runs in a threadpool. Use async def only with async libraries; def covers blocking calls. Red flag: claiming async is automatically faster or awaiting inside def.
Async Path Operations in FastAPI
FastAPI path operations can be async, letting the server switch to other requests during I/O waits. Declare dependencies and sub-dependencies async when they await external calls.
How would you design the backend check for a report quota?
Tests reliable quota enforcement without race conditions. A strong answer uses atomic counts or DB constraints, validates at the service layer, and surfaces a clear 4xx. A red flag is a non-atomic SELECT-then-INSERT pattern.
How does Node.js handle thousands of connections on one thread?
This tests non-blocking I/O: Node.js runs one thread for an event loop while the OS handles sockets via epoll or IOCP, resuming callbacks when data arrives. Mention the thread pool for DNS and fs work. A red flag is claiming threads spawn per request.
Describe a pattern for background Core Data fetches and UI updates
This tests NSManagedObjectContext concurrency and queue confinement. Strong answer: create a background context, fetch, pass objectIDs or structs to main, then main context fetches by ID to update UI. Red flag: passing NSManagedObjects across threads.
Thread Sanitizer catches data races in Swift
Thread Sanitizer turns flaky race crashes into reproducible reports by monitoring memory accesses at runtime. Use it in Xcode to catch unsynchronized cross-thread reads and writes. It only catches races that execute during your test run, so coverage matters.
withCheckedThrowingContinuation: Bridge Callbacks to Async/Await
withCheckedThrowingContinuation bridges legacy completion-handler APIs into async/await. Wrap one-shot callback-based work so callers use try await instead of nested blocks. The footgun is resuming twice or never, which checked runtimes catch in debug builds.
Get Concurrency bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.