Ch.71: Data Warehouse System Design: Read Less, Answer Faster
Outline
- 0:00 Warehouse answers
- 0:11 Read less before scaling
- 0:28 Data and query paths
- 0:42 Coordinator and admission
- 0:56 Prepare data during reads
- 1:09 Functional requirements
- 1:38 Durability, consistency and limits
- 1:49 Scope and measurement units
- 2:09 Three completion points
- 2:27 Count requested bytes
- 2:37 Read needed columns
- 2:55 Whole forms versus field stacks
- 3:13 Conditional savings; no runtime promise
- 3:52 Durable intake before publication
- 4:14 The loading dock and inventory
- 4:32 Publish immutable file lists
- 4:46 Lost publication reply
- 5:06 Batch identity versus event identity
- 5:17 Writers and stale versions
- 5:35 What file metadata can prove
- 5:46 Skip a file only with evidence
- 6:07 Unhelpful file ranges
- 6:42 Projection versus file pruning
- 7:09 Choose one snapshot per query
- 7:26 New data during a running query
- 8:02 Retain files for active readers
- 8:36 Scan disjoint ranges
- 8:49 Combine regional partial sums
- 9:08 Send partial answers, not rows
- 9:27 Limits on parallel speedup
- 9:56 Nearly unique grouping keys
- 10:19 Shuffle partial sums by key
- 10:38 Optional early grouping
- 11:00 The cost of reducing transfers
- 11:22 Spill unfinished groups to disk
- 11:46 Admit work when memory fits
- 12:13 Idle CPUs cannot supply memory
- 12:31 Released memory and data freshness
- 12:41 Enforce worker and storage limits
- 13:07 Cancellation and the deadline
- 13:29 Restart an incomplete attempt
- 14:00 Ignore output from old attempts
- 14:27 Complete the original snapshot
- 14:46 When the coordinator dies
- 15:09 Requesting a retained version
- 15:24 Separate waiting, planning and scanning
- 15:40 Exchange and spill bottlenecks
- 15:52 Diagnose an expensive file layout
- 16:02 Measure publication freshness
- 16:24 Architecture revisited
- 17:04 Fewer bytes, explainable answers
Transcript
0:00 A cloud data warehouse keeps history for questions like yesterday's revenue by region. The dashboard wants regional sums from a billion rows. All that history, and you're still waiting for a few totals. We'll follow one SQL request, cut unnecessary reads, share the work and hold one table version while new data arrives. It can be an expensive way to draw a small chart. Let's make the servers read less before adding more. How does our dashboard send work to those machines? With that dashboard request in mind, our architecture has two routes.
0:31 Input batches become durable files that store each field's values together. A catalog publishes which files make up the table. Queries take a separate route to workers that read those published files. So a query coordinator asks the catalog for the table's file set and schema. It chooses the workers' tasks and combines their answers. Admission makes the request wait for resources. Why keep receiving data separate from running a query? Because queries read data that has already been published. New batches can be prepared alongside that work, then become part of a later table version.
1:05 We'll return to this map. What exactly are we promising the dashboard? Before choosing storage, our functional requirements start with that reporting team: accept named batches, publish table versions, and answer read-only filters and grouping. Return the chosen version with each result and support cancellation. Suppose the reporting team uploads yesterday's sales and gets success, but its dashboard is unchanged. Did we accept the bytes or publish a table version? The dashboard alone can't tell.
1:34 Intake confirms stored bytes; publication reports the committed version. Our non-functional requirements protect acknowledged data after a crash, keep workers on one view and bound the resources a request can consume. Authorization and schema checks happen before it runs. I'd also make the scope explicit: one cloud deployment region, append-only inputs, and our dashboard query. We're not implementing every SQL feature or updating individual rows in place. Agreed. Amounts are already whole numbers in a defined unit, such as cents.
2:04 We're adding that measure, not deciding what counts as revenue inside the query engine. And accepting a batch, publishing a table, and returning an answer are three separate completion points. Otherwise one cheerful success message can hide where the data actually stopped. Exactly. We'll measure the delay between those points. The next decision is how much data the query should request at all. With our workload defined, take a deliberately simple example: a billion rows, 100 fields per row, 8 bytes per field.
2:34 That is 800 gigabytes of uncompressed field data. Our query needs the event time, region and amount. 3 fields rather than 100. If those columns can be read separately, that's 24 gigabytes before compression or excluding any files. So most of that first read was for fields we weren't using. That is columnar layout: grouping values by field. Row layout groups fields by record, like whole forms. Column layout is a separate stack for each box on the form. We need 3 stacks out of 100. It's easy to reach for more machines before asking what we're making them read.
3:09 How do we also avoid the days the dashboard didn't ask about? Use metadata that can rule out files. If our particular layout lets us exclude 99% of those column bytes, the example reaches 240 megabytes. Provided that layout really supports the exclusion. 3 columns is a query choice; 1% surviving is another assumption. Compression would be a 3rd effect. Right. Those are byte counts, not a promised runtime. Snowflake's public architecture describes compressed column storage with query compute separate from durable storage; source links are in the description.
3:43 So the storage format decides what work we can avoid. We should understand how those files become a table before trusting their metadata. Before files become queryable, start with an input batch carrying a stable ID. We durably accept it, then build immutable column files and metadata describing their schema, row counts and useful value ranges. The files are already there. Why not let queries list the storage folder? A writer can still be preparing part of a batch, or leave abandoned files. Think of paintings arriving on a museum's loading dock.
4:17 Right, delivery isn't the exhibit. The catalog supplies its inventory: these files belong to this table version. Only when the required files are ready does one transaction publish that inventory and record the batch it contains. Yes. Call the existing file list History. The current inventory page refers to it. Our arriving batch adds a file list called Tuesday. The replacement names both History and Tuesday, leaving the original list unchanged for an older query. Suppose publication succeeds but its reply disappears.
4:50 If the writer retries the batch, how do we stop another copy entering the table? Look up that stable batch ID in the catalog. Our transaction records the batch outcome with its resulting table version, so a retry finds the existing publication instead of adding it again. That protects this batch replay. If an upstream producer sends the same business event under two different batch IDs, we still need an event-identity contract elsewhere. That distinction matters. Suppose a second writer prepares a Wednesday batch from the History-only page.
5:21 Tuesday publishes first. The catalog rejects Wednesday's stale starting version. That writer refreshes its inventory and includes History, Tuesday and the new Wednesday list. Otherwise its commit could hide Tuesday's published sales. So the catalog names a published version. What can tell us which of its files to open? Conservative bounds on the values in each file. The planner can use those bounds before scheduling a scan. With those bounds, imagine our dashboard asks for Tuesday. One file's event times run from Monday morning to Monday night.
5:53 Its range proves that it cannot contain a Tuesday row. So the planner skips that file without opening its columns. Another file spans Monday through Wednesday; it stays, and the worker evaluates the exact Tuesday filter on its rows. What if we sort by customer ID, and almost every file contains dates from the whole month? Then those time ranges tell us very little. We may scan nearly every file. Snowflake's storage documentation connects how values are arranged with how many files a query can skip.
6:23 Ah, the metadata didn't fail. We arranged the data so it couldn't rule much out. That matters when someone promises our earlier 1-percent scan. Yes. Organize around useful access patterns, then measure the tradeoff. Reorganizing files costs work too, and helping one filter doesn't automatically help every query. I'd rather read an uncertain file than lose a matching row. Missing statistics mean we keep it, not quietly treat the file as empty. Agreed. Projection chooses field stacks inside a file; pruning rejects a whole file when its range rules it out.
6:58 In our example, we choose 3 fields, then leave the Monday-only bundle unopened. Those matching files could belong to different table versions. How do the workers agree on which one they're querying? There's another choice before execution: the table version. A snapshot records a coherent version's schema and data files. The coordinator selects one and binds it to this query. Suppose yesterday's late-arriving records are published while workers are already scanning. Show me how that race ends. Say the query selected snapshot 7.
7:28 The late batch creates snapshot 8. Every worker for this query stays on 7, even workers that start after 8 becomes current. So one worker doesn't include the late rows while another uses the earlier file set. The answer describes 7, and the next query may describe 8. Yes. Iceberg's specification describes this separation between immutable snapshots and publishing new table metadata. Our result reports its selected version, so “consistent” doesn't secretly mean “the newest possible data.” I'd find a precise older answer easier to explain than a newer-looking answer assembled from different moments.
8:02 But what stops cleanup from deleting snapshot 7's files during the query? We track active readers as well as retained snapshots. File cleanup waits until neither needs a file. Publishing a replacement doesn't authorize deleting whatever the old query is still reading. So keeping the inventory isn't enough. Cleanup must preserve the files it names while that older query is reading. That retention promise is part of keeping the answer consistent. Right. The coordinator now has a schema, a stable set of eligible files and the columns to request.
8:33 We can divide the actual work. Once that snapshot is fixed, split the selected files into smaller, nonoverlapping chunks for workers to scan. Workers read the needed columns, test the date condition and calculate sums for each region they encounter. For example, one worker finds west equals 3 and east equals 2. A second contributes another 7 for west. The final combination gives west 10 and east 2. Each input range belongs to the calculation once. We're combining sums over disjoint records, not letting two workers both claim the same file range.
9:07 Right. With a small number of regions, a worker can send a few regional sums instead of all those matching rows. That changes the network work as well as the arithmetic. Nice, the coordinator needs their partial answers, not a copy of every sale. But is adding workers enough to keep the time falling? Only until another resource dominates. Workers can compete for storage bandwidth or the network, and combining their output takes time. Parallelism is useful work distribution, not a linear-speedup guarantee.
9:39 Google's historical Dremel paper connects columnar reads with a tree that combines partial results. We're using that public idea without borrowing its benchmark timings for our system. Exactly. The savings depend on what we're grouping. Can you show a grouping where those partial answers barely shrink? For that contrast, suppose the dashboard groups by a nearly unique transaction ID instead of region. A worker may finish with almost as many groups as input rows. Our regional request sends a short scoreboard.
10:07 The transaction-ID request can leave an entry per sale. Local grouping buys those two requests very different savings. For our regional query, where do west's contributions meet? Route west's subtotal of 3 and its subtotal of 7 to the same receiving worker, which finishes west 10. Sending contributions for each key to its assigned worker is a shuffle. Those transfers use the network, and a dominant key can give one receiver much more work. Ah, we can choose where to do the combining. Forming worker subtotals before the transfer is optional; producing the final SQL groups isn't.
10:44 In a 2024 engineering post, Snowflake's builders describe an added grouping operation that can switch off during execution when its reduction isn't worth the cost. That complicates the rule I was about to use. What would make us switch our early grouping off? For the nearly unique IDs, take a fictional worker trace: grouping takes 8 milliseconds and the following send saves 2. That adds 6 milliseconds on this sequential path. Here we'd switch it off, while still computing the required final groups.
11:15 Sending fewer entries can still cost more overall. What happens if the unfinished group totals don't fit in memory? Write some unfinished totals to temporary files, then read them back in manageable pieces to finish the groups. That is spill: extra reads and writes in exchange for memory relief. Bound that temporary storage too, and fail clearly if the work cannot finish within its limits. Right. Both the network transfers and those temporary files belong in the cost estimate. How does admission stop one query from taking the whole pool?
11:46 Now the reporting team's late batch is building files when someone opens the dashboard. Give this fictional pool 16 gigabytes for query memory. The batch's file build has reserved 12; the dashboard query requests 6. Can we admit it? No. 4 gigabytes remain, so that query waits. Admission checks reservations against the budget before starting work. A separate interactive pool can protect dashboard access, if predictable response justifies paying for that capacity. I think I'd still try to squeeze it in while CPUs look idle.
12:17 Wouldn't we otherwise leave machines doing nothing while requests wait? An idle CPU doesn't supply the missing memory. Spare capacity has to cover the reservation. Storage and network can also constrain a query. Fair enough. Suppose file building finishes and releases its reservation, but publication hasn't happened yet. Our dashboard is admitted with 6 gigabytes. What if the group totals need more than we estimated? Our coordinator divides that reservation among the query's workers. Each worker checks its allowance before growing group state.
12:48 If the next allocation would exceed it, the worker spills unfinished totals and processes smaller pieces. If bounded temporary storage also runs out, it fails the attempt. The caller gets a resource-limit error, never a partial regional answer. So the estimate doesn't grant permission to consume whatever memory happens to be free. And if the person closes the dashboard before that work finishes? The caller still needs cancellation. Stop scheduling new tasks, tell active tasks to stop, release temporary state and record the outcome.
13:19 Closing a dashboard tab doesn't prove the server stopped its work. Yeah, and admission wait counts against the dashboard's deadline. We should include that wait when explaining a late answer. But cancellation isn't the only reason an attempt ends. Our dashboard's first worker has returned west 3 when another worker dies. Our first design discards the entire attempt and restarts from the same snapshot. A reviewer might say, 'Retry only the worker that failed.' Wouldn't that avoid repeating all the successful work?
13:48 It can. I think whole-attempt restart is a defensible first design because its recovery protocol is simpler. Durable stage outputs and individual retries are refinements if the measured waste warrants them. Then late messages need attention. A supposedly dead worker might finish and send its old partial after the replacement attempt starts. Tag messages with query and attempt identity. The coordinator combines output only from the active attempt and ignores the previous attempt's messages, including plausible-looking successful sums.
14:18 So if attempt 1 sent west 3, and attempt 2 sends west 3 again, we don't add both. Attempt 2 must supply its own complete required contributions. Exactly. The original attempt's result stays unpublished. Only after all required work succeeds does the query produce one complete answer associated with its snapshot. And a retry against the newest snapshot would be a different request contract. Holding the original version keeps recovery from quietly swapping the data under our request. What if the coordinator itself dies before the dashboard gets its answer?
14:50 The caller sees an unknown outcome, and a replacement coordinator won't adopt that execution. The dashboard can submit a new read-only query from the beginning, with none of the old partials. Ah, the user retries the dashboard request, while worker recovery retried one execution. That new request could select newer data. Right. Its result names the version it actually read. If the team needs the old calculation exactly, it must request that original version while its files are still retained. Otherwise we fail clearly rather than substitute different data.
15:23 With those completion rules defined, where would you look first if this dashboard suddenly gets slower? Start with admission wait, planning time and scan time. If our example still scans 240 megabytes but admission wait rises, changing the file filter won't fix the queue. Right. Then inspect data exchange, spill and the slowest stage. If worker CPU stays modest while bytes moved between workers jump, check the grouping plan and network before adding more scan workers. I'd also compare bytes selected with bytes available.
15:54 If every time range overlaps every file, the query can be correct while our layout makes it unnecessarily expensive. And measure input acceptance separately from table publication. A quick query over yesterday's snapshot isn't evidence that ingestion is current. Yeah, a fast stale dashboard is still stale. Its result version and freshness should be visible enough that the person reading regional totals knows what those numbers describe. Let's trace that waiting time and freshness across the full map.
16:24 So back on the same architecture, the dashboard waits at admission until its 6-gigabyte reservation fits. The coordinator then pins its query to version 7 and assigns the selected columns and files to workers. With its files already durable, the Tuesday batch now publishes snapshot 8 through the catalog. Our running query keeps 7. Its workers can still read that version's files while the new batch becomes visible to later requests. The workers filter and combine their contributions into west 10 and east 2.
16:54 This completed result names 7, so the people reading the chart know which published sales it includes. We can explain the time spent waiting separately from the age of its data. With that whole path in view, the dashboard's small result never guaranteed a small query. We made it cheaper by requesting fewer fields, excluding files with evidence and combining work where partial answers really shrink. And when that answer arrives, we know which table version it read and what a retry would repeat. I'd price the machines after finding the bytes we can avoid.
17:25 That feels much easier to defend. Thanks for listening to Learning Podcasts.