Interview: March gained $50 after the deploy, and the months don’t add up
date_trunc follows the session time zone, and BETWEEN counts the shared midnight twice. timestamptz, AT TIME ZONE, and half-open ranges.
More on Ticket interviews
- Database Interviews in the AI Era: The Ticket Format
- Interview: the same job runs twice
- Deadlock Interview Question: Find and Fix It in SQL
- Slow Query Interview: One Keyword Made It 40× Slower
- Interview: rate limit is 2/min, 30 requests get through
- Interview: “just add an index” slowed ingestion
- Interview: “I changed my name, refresh shows the old one”
- Interview: importing 10M rows takes six hours
- Interview: everything got slow and the disk keeps growing
- Lost Update Interview: Wallet Balance Wrong Under Load
- Interview: API p99 jumps 10× every night at 2 am
- Interview: profile lookups got 40× slower, writes are fine
- Interview: inserts stall, and only one page is hot
- Interview: the write succeeded, the next read shows an empty cart
- Interview: inventory stayed locked after the coordinator restarted
- Interview: for four minutes, both regions took orders
- Interview: shoes show a 0% discount, then the report crashes
- Interview: the new branch’s dashboard takes 38 seconds
- Interview: the index is right there, make Postgres use it
- Interview: warehouse and checkout overwrite the same order
- Interview: the bestsellers report now takes nine minutes
- Interview: an analyst query locked checkout
- Interview: the member is active and the email went out twice
- Interview: one shard is at 96% CPU and the other is idle
- Interview: the menu is slow, and the proposal is event sourcing
- Interview: four dashboards disagree about whether the database is slow
- Interview: checkout got slow the hour the warehouse job started
- Interview: the query is fast in staging and slow in production
- Interview: login looks up an email and reads the whole customers table
- Interview: the proposal splits one database into three shards
- Interview: the order page joins four tables on every view
- Interview: every page view is a read-write query on the leader
- Interview: Sarah and John both debit version 1
- Interview: the CTO read a blog post and wants to move Postgres to MySQL
- Interview: one table takes 50,000 writes a second, another feeds dashboards. Which engine for each?
- Interview: EU users wait on the ocean for every write, can both regions take writes?
- Interview: users search cars by color, but the table is sharded by car id
- Interview: we added a fourth node and most of the data moved
- Interview: two people book the same room at noon, both get a confirmation
- Interview: everything is on the strongest consistency and far requests crawl
- Interview: the order is saved, the message to search and email never left
- Interview: rename a column on a 600 GB table while 30 servers keep serving traffic
- Interview: orders go to 16 shards in 2 regions, what should the order id be?
- Interview: one celebrity posts, and every timeline in the app slows down
- Interview: 5,000 customers share one database, and one of them slows down everyone
Keep learning
Overview
= startUtc && (inclusiveEnd ? t Same four sales. Session time zone, then the month predicate. session TimeZone Time zone month predicate = start AND March + April every sale Sale B is 2020-04-01 00:00 in New York, which is still 21:00 on March 31 in Los Angeles. date_trunc without AT TIME ZONE follows the session, so this container and that laptop disagree by $50. In New York, sale B is exactly midnight at the start of April. BETWEEN includes both ends, so B is in March and in April. The two months add up to more than the table. BETWEEN includes both ends. In this zone no stored sale sits on that shared instant, so the months still add up. Switch to New York, where B is exactly midnight, and the same predicate counts it twice. The half-open range keeps B in exactly one month. March + April equals the table.
March gained $50 after the deploy, and the months don’t add up
The monthly query borrows the session’s time zone, and BETWEEN counts midnight twice. Two small bugs, one confused finance team. AT TIME ZONE $50 moved months, and months sum past the total
March and April sales changed, and they no longer sum to the total
The new container no longer sets the database TimeZone. March + April exports are $50 more than the table total. March shift April shift month sum $50 over 15, then 100k Restated: one sale changed months with the zone. One sale is counted in two months.
Where does the query learn the time zone?
sold_at is timestamptz. date_trunc converts it to the session TimeZone, then truncates. The query never names a zone. BETWEEN keeps both endpoints. A sale at exactly 2020-04-01 00:00 New York is in March and in April.
Two bugs, two different wrong totals
Did the prices change? compare sum(price) before and after No, the grand total is the same. Money moved between months: a boundary bug, not a missing row. What changed in the deploy? image diff and SHOW timezone The old server set Los Angeles. The new one uses the default. date_trunc follows that setting. Which sale can sit in two buckets? a row exactly on the end instant Sale B: April 1, 00:00 in New York is still March 31, 21:00 in Los Angeles. Why is March + April more than the table? read export.sql BETWEEN includes both ends. Both months contain April 1, 00:00, so B is in both. One stored instant, two clocks, two different months.
Name the zone, and stop the ranges overlapping
Month is stable Months add up Today: session zone + BETWEEN SET TIME ZONE on the pool AT TIME ZONE + half-open range Only fixing both bugs makes both columns green. The zone lives in the query, so a container default can’t move it. Half-open ranges mean neighbouring months never share an instant. One test per bug: zone shift, and months summing past the table. Blocks the quick “set the server zone back” non-fix.
No AI from here
What does a timestamptz actually store? “11:00 New York” literal you type 15:00 UTC what is stored Session zone applied on the way out One instant in UTC. The typed zone is used, then thrown away. Plain timestamp stores clock fields only. It is not an instant. date_trunc and extract convert to the session zone first. That conversion is why two sessions disagree. stored as UTC session zone is applied on the way out timestamp has no zone The day the clock springs forward is 23 hours. Where does that bite? daylight saving local times that never exist Anywhere code assumes a day is 24 hours. Adding ‘1 day’ or grouping by bare date can drop or double an hour. Subtracting two timestamptz values gives the true 23 hours. the gap and the overlap elapsed interval vs local clock Why is BETWEEN the wrong tool for a month, a decade, or a bucket? BETWEEN start AND next Both ends included. Neighbours share midnight. >= start AND < next Half-open. Ranges tile with no overlap. It includes both ends, so neighbouring ranges overlap. Half-open ranges (start included, end excluded) tile cleanly. Days, months, number bins: all want the half-open shape. inclusive ends overlap midnight batch jobs hit it Which of these still depends on the session zone? silent conversion extract(hour …) AT TIME ZONE ‘…’ explicit: safe date_trunc, extract, and ::date all convert through the session zone. Fix: sold_at AT TIME ZONE ‘America/New_York’, then truncate. Literals need a zone too, not a bare clock time. A store’s busiest hour needs that store’s own zone. names the three silent conversions AT TIME ZONE on the column SET TIME ZONE in the connection pool would make today’s numbers match. Why is that not the fix? Pool default Every new service, laptop, or replica can differ. Zone in the query Same month, wherever it runs. Every other client has its own zone, so the month moves again. BETWEEN still double-counts midnight under any zone. the query names the zone BETWEEN is a separate bug a pool default drifts
Stores span New York and Los Angeles
Which clock is a “month”? Company zone, written on every query Finance gets one March, and months tile. Store-local hours become a separate query. Stable months Local-hour honesty Double count Each branch’s own zone inside the month group Right for “busy hour in that city”. But company March mixes two calendars. SET TIME ZONE on the pool to New York Matches today, until another client uses another zone. BETWEEN still double-counts. Store sold_at as timestamp without time zone Freezes whatever clock inserted the row. The column stops being a real instant.
Have one ready
Tell me about a report that changed when it ran somewhere else. Which total moved, which stayed. Session zone, or shared endpoint. A midnight row tested under two zones.
Did you show these?
Told a moved bucket from a lost row Named session TimeZone as a date_trunc input Put AT TIME ZONE in the query Explained the 23-hour day Showed BETWEEN double-counting midnight Switched to a half-open range Refused pool-wide SET TIME ZONE as the fix
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.