Execution Models, Go Concurrency, and Choosing a Database
System DesignModel answerLast updated
Explain how sync/async differs from blocking/non-blocking, when Go channels or mutexes fit best, and how relational and NoSQL stores compare for backend workloads.
Three short conceptual questions that a backend engineer should be able to answer with precise definitions and concrete examples.
Part 1: Execution models
- Define synchronous and asynchronous execution.
- Explain why this is a different axis from blocking and non-blocking I/O.
- Give one backend example of each, such as serving an HTTP request or calling a downstream service.
Part 2: Concurrency in Go
- Describe, at a high level, how Go runs concurrent code (goroutines and the runtime scheduler).
- Compare coordinating work by passing messages over channels with coordinating it by sharing memory behind locks.
- Say when you would choose each, and name the typical failure modes: deadlocks, data races, and goroutine leaks.
Part 3: Relational vs NoSQL databases
- Compare relational databases with the main NoSQL families (key-value, document, wide-column).
- Discuss the trade-offs in:
- data modeling and query patterns
- transactions and consistency
- scaling (vertical vs horizontal)
- operational burden
- Give a few workloads where you would strongly pick SQL, and a few where you would strongly pick NoSQL.
Aim for a structured answer that separates concepts people tend to confuse and supports each claim with an example.
Hints
Hint 1
Treat sync/async as a question of how the caller's control flow relates to completion, and blocking/non-blocking as a question of what the thread does while waiting. Then try placing examples in a 2x2 grid.
Hint 2
For Go, a useful rule is: channels move ownership of data or orchestrate work; mutexes and atomics protect a small piece of shared state. For each pitfall, think of one concrete scenario that causes it and one tool that prevents it (context cancellation, the race detector, consistent lock ordering).
Hint 3
For databases, start from access patterns rather than technology: what are the queries, how much cross-entity consistency is needed, and how will the data grow? Remember that many NoSQL systems have gained transactions and many SQL systems can scale out, so frame differences as defaults and trade-offs.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Synchronous vs asynchronous
Definitions
- Synchronous: the caller starts an operation and does not move on until it finishes. Starting and completing are tied together in the control flow.
- Asynchronous: the caller starts an operation and carries on. The result is delivered later through a callback, a future/promise, an
await, or a message.
Blocking vs non-blocking is a separate axis. It describes what the thread does while the I/O is pending.
- Blocking: the OS parks the thread until data is ready (a plain
read()on a socket). - Non-blocking: the call returns immediately, for example with
EAGAIN, and readiness is discovered throughepoll,kqueue, orio_uring.
| Blocking | Non-blocking | |
|---|---|---|
| Sync | Thread-per-request server calling read() | Polling a non-blocking socket in a loop |
| Async | Handing a blocking call to a thread pool and returning a future | Event loop (Node.js, asyncio, Netty) |
Go is a good illustration: goroutine code reads as synchronous and blocking, but the runtime uses non-blocking sockets and a netpoller, parking the goroutine and freeing the OS thread.
Backend examples
- Synchronous:
GET /balancequeries the database and returns the row. The client needs the answer immediately. - Asynchronous:
POST /transferwrites the transfer, enqueues a "send notification" job on a queue, and returns without waiting for it. - Concurrent fan-out inside one request: call the fraud, limits, and profile services in parallel and await all of them. Latency becomes about
maxof the three instead of thesum.
import asyncio
async def call(name, delay):
await asyncio.sleep(delay) # stands in for non-blocking network I/O
return name
async def sequential(): # ~0.6s
return [await call("fraud", .2), await call("limits", .2), await call("profile", .2)]
async def concurrent(): # ~0.2s
return await asyncio.gather(call("fraud", .2), call("limits", .2), call("profile", .2))
Trade-offs: async improves throughput and latency for I/O-bound work but complicates error propagation, retries (use idempotency keys for anything like payments), ordering, and tracing. Common mistake: calling a blocking function inside an event loop, which stalls every request on that loop.
Part 2: Go concurrency
Model
- Goroutines are lightweight, runtime-managed tasks with small, growable stacks (a few KB), so tens or hundreds of thousands are practical.
- The scheduler is M:N: goroutines (G) are multiplexed onto OS threads (M) via logical processors (P).
GOMAXPROCSsets the number of Ps, defaulting to the core count. Idle Ps steal work from busy ones. - Goroutines yield on channel operations, blocking syscalls, and network I/O. Since Go 1.14 they can also be preempted asynchronously, so a tight loop cannot starve others.
Channels vs locks
| Channels | Mutex / atomics | |
|---|---|---|
| Idea | Transfer ownership of data between goroutines | Several goroutines touch shared state under a lock |
| Best for | Pipelines, worker pools, fan-out/fan-in, signaling, cancellation, backpressure | Caches, counters, maps, small bits of state |
| Downside | More overhead; can obscure simple logic | Contention; easy to forget a lock |
Rule of thumb: use channels to orchestrate work or hand off ownership, and use a mutex or atomic to guard state. Wrapping a simple cache in a goroutine plus request channel is usually over-engineering.
func process(ctx context.Context, jobs []Job, workers int) map[string]int {
var (
mu sync.Mutex
counts = map[string]int{}
wg sync.WaitGroup
ch = make(chan Job)
)
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range ch {
r := handle(j)
mu.Lock()
counts[r]++
mu.Unlock()
}
}()
}
loop:
for _, j := range jobs {
select {
case ch <- j:
case <-ctx.Done():
break loop
}
}
close(ch) // producer owns the channel
wg.Wait()
return counts
}
Pitfalls
- Deadlocks: an unbuffered send with no receiver; two goroutines taking locks in opposite orders (fix with a consistent order); ranging over a channel nobody closes. The runtime only reports a deadlock when all goroutines are asleep, so partial deadlocks look like hangs.
- Data races: concurrent map writes (which crash), copying a struct that contains a mutex, and loop-variable capture in older Go versions. Run
go test -race. - Goroutine leaks: a goroutine blocked sending to a channel whose reader gave up after a timeout. Pass a
context.Context,selectonctx.Done(), use a buffered channel of size 1 for single results, and watchruntime.NumGoroutine()and pprof. - Channel panics: sending on or closing a closed channel panics. Only the sender closes, and a nil channel blocks forever.
Part 3: SQL vs NoSQL
Families
- Key-value (Redis, DynamoDB in simple mode): lookup by key; very fast and simple; limited querying.
- Document (MongoDB, Firestore): nested JSON-like records; flexible schema; good for aggregates read as a unit.
- Wide-column (Cassandra, HBase): partitioned, write-optimized, query-first table design; suited to huge time-series or event data.
Trade-offs
| Dimension | Relational | NoSQL (typical) |
|---|---|---|
| Modeling | Normalized schema, joins, ad hoc queries | Model around known access patterns; denormalize, duplicate data |
| Transactions | Full ACID across rows and tables | Often single-key or single-partition atomicity; some offer limited multi-document transactions; many offer tunable or eventual consistency |
| Scaling | Vertical first, then read replicas; sharding is possible but harder | Designed for horizontal partitioning and high write throughput |
| Operations | Mature tooling, strong schema enforcement, simpler reasoning | Schema flexibility but pushes integrity into application code; cluster tuning, compaction, and repair can be heavy |
The lines blur: modern SQL systems scale out and support JSON, while several NoSQL stores have added transactions. Present differences as defaults, not absolutes.
When to choose which
- Strongly SQL: ledgers and payments, inventory and orders, anything with multi-row invariants, reporting that needs joins and ad hoc queries.
- Strongly NoSQL: session or cache storage (key-value), user-profile or content blobs with variable shape (document), high-volume event or telemetry ingestion with predictable partition-key queries (wide-column).
A solid close: start with the access patterns and consistency needs, default to SQL when unsure, and add NoSQL where scale or data shape clearly demands it. Polyglot persistence is common.
Common mistakes to avoid
- Equating async with non-blocking, or with parallelism.
- Claiming "channels are always better" in Go.
- Saying "NoSQL scales, SQL doesn't," or "NoSQL has no transactions."