#postgres
PostgreSQL queries, indexes, extensions, tuning and operations.
Posts tagged #postgres
Blameless review: the 'quick' migration that blocked every write to our orders table
Short incident review, because the lesson is more useful than the embarrassment. What happened A normal Tuesday deploy at 08:12 ran two migrations generated by our migration tool: ALTER TABLE orders ADD COLUMN priority int NOT NULL DEFAULT 0; CREATE INDEX orders_priority_idx ON orders (priority); Both look harmless. Since Postgres 11, adding a column with a constant default does not rewrite the table, so the ALTER…
Go + Postgres: ¿pgx directo o database/sql? (y cómo manejan el pool)
Parce, sigo aprendiendo Go con tincho (gracias maestro) y ya estoy pasando un servicio pequeño de Node a Go. Tengo dudas con Postgres: ¿Usan pgx directo ( pgxpool ) o database/sql con el driver pgx/v5/stdlib ? Leí que pgx directo es más rápido pero no sé si vale la pena. ¿Cuántas conexiones ponen en el pool? En Node tenía max: 10 en pg y no sé si en Go es igual. ¿sqlc o escribir las queries a mano? El servicio es…
In ten days the clocks go back. Is your medication schedule ready?
On the last Sunday of October most of Europe goes back from summer time to standard time, and the hour from 02:00 to 03:00 happens twice. For most software this is a small annoyance. In a hospital it can mean a dose documented twice, or an infusion total calculated over the wrong number of hours. Siobhan wrote a very good story here some weeks ago about a renewal test that failed one night a year. This is the…
Daily sales report across timezones: which day does an order at 11:30pm Bangkok belong to?
We store created_at as timestamptz. Until now all markets were UTC+8 (Singapore, Malaysia) so we just did: select (created_at at time zone 'Asia/Singapore')::date as day, sum(amount) from orders group by 1; Now we add Thailand (UTC+7). Order at 23:30 Bangkok time is 00:30 next day in Singapore. Thai team want it in their day, regional report want one number per day. Options: convert each order using its market…
N+1 no JPA: como achei 1.201 queries numa tela de listagem (e matei com 3 linhas)
semana passada o DBA abriu chamado: "a tela de pedidos tá derrubando o Postgres, precisamos aumentar a instância". eu fui olhar antes de alguém gastar dinheiro. a tela lista 600 pedidos com o nome do cliente e a quantidade de itens. coisa simples. liguei o log de SQL e fui pegar um café. quando voltei o terminal ainda tava rolando kkkkk como achar # application.properties logging.level.org.hibernate.SQL=debug…
Django REST Framework: still N+1 queries after select_related, what am I missing?
One of my mentees brought this to me and now I am also stuck, which is humbling. We have a simple endpoint listing courses. Each course has a teacher (ForeignKey) and many tags (ManyToMany), and the serializer also shows how many students are enrolled. class CourseSerializer(serializers.ModelSerializer): teacher = TeacherSerializer() tags = TagSerializer(many=True) student_count = serializers.SerializerMethodField()…
Payout worker queue in Postgres: SKIP LOCKED is holding transactions open for 30s, better way?
We have a payouts table and 4 worker processes that pick pending payouts and call the bank API. Right now each worker does this: begin; select * from payouts where status = 'pending' order by created_at limit 10 for update skip locked; -- call bank API for each row (can take up to 30s) update payouts set status = 'sent' where id = ...; commit; It works, no double picks. But the transaction stays open during the HTTP…
Storing high-frequency meter data: plain Postgres, TimescaleDB, or something else?
We are getting more charger and meter data than our current setup was designed for. Right now it is about 40,000 devices sending a reading every 15 seconds, so roughly 230 million rows per day, into a single Postgres table with a B-tree index on (device_id, ts) . Inserts are still fine, but queries over a week for one site are getting slow and the table is huge. Typical queries: last 24 hours for one device, at full…
latest row per customer without a correlated subquery that takes 40 minutes?
doing a take-home for a data engineering role (job hunt day 187, grand, all grand). table is basically: customer_events ( id bigint primary key, customer_id bigint, event_type text, payload jsonb, created_at timestamptz ) about 120M rows in their description, i've a 5M sample locally. they want the latest event per customer. my first go: SELECT e.* FROM customer_events e WHERE e.created_at = ( SELECT MAX(created_at)…
the AI wrote me a running total that was 'almost right'. almost right is the worst kind
ok quick one because this bit me today and i want to save someone an afternoon. asked an ai assistant for a running total of revenue. it gave me this, which looks totally fine: SELECT order_date, amount, SUM(amount) OVER (ORDER BY order_date) AS running_total FROM orders; ran it, numbers looked plausible, almost shipped it to the dashboard. then i noticed the running total jumped by the same amount on every row with…
Postgres count(distinct) on 80M rows very slow, any trick?
Daily active customers query take ~40s, dashboard timeout: select date_trunc('day', created_at) as day, count(distinct customer_id) from orders where created_at >= now() - interval '90 days' group by 1 order by 1; Table ~80M rows, index on created_at. Postgres 15. EXPLAIN show big Sort spilling to disk. Tried increase work_mem to 256MB, bit faster but still 25s. Is count(distinct) just slow in Postgres? Thinking to…
The Friday deploy a power cut saved (and the idempotency key that saved us the next time)
Howzit. Two stories, one lesson, and the lesson is not "don't deploy on Friday", sorry. Story one A few years back, Friday 16:30, I'm about to push a change to how we retry failed card authorisations. Tests green, reviewer happy, I'm feeling lekker. I type the command and the power goes. Whole block. The inverter was smaller back then, so the laptop is fine but the fibre box is not. No internet, no deploy. I sulked,…
Your Go service has 600 Postgres connections and uses 6 of them
Last month a routine scale-up took down our orders database. Not CPU, not disk. Connections. Postgres said FATAL: sorry, too many clients already and every service that touched it fell over together. How we got there 40 pods of one Go service, each with a pgx pool. Nobody had set MaxConns , so pgxpool used its default: the larger of 4 and runtime.NumCPU() . Our nodes have 16 cores. 40 times 16 is 640 possible…
How do you store money amounts in your database?
What is your main production database? No 'it depends', pick one.
A double-entry ledger in Postgres, the boring way that works
Every fintech I have worked at started with a balance column on the users table. And every one of them later spent months moving away from it. If you are building anything where money moves between parties, wallets, marketplaces, lending, start with a ledger. It is less work than it sounds and Postgres gives you almost everything you need. This is the design we run in production now. Nothing fancy. Boring is the…
Idempotency keys in Go: the version that survives a double tap and a dead inverter
Customer taps Pay. The request goes out on a 3G connection in Onitsha, reaches our API, the charge succeeds, and the response dies somewhere on the way back. The app sees a timeout and retries. Without protection, that is two charges and one very angry customer calling the merchant, who calls us. Same thing happens when NEPA takes light in the middle of a request and the client's inverter takes three seconds to kick…
Idempotent payment endpoints in Go and Postgres: the pattern that stopped our double charges
For six months we refunded somebody almost every Monday. Same story every time: customer on a bad connection taps Pay, the request reaches us, the PSP charges them, our response never reaches the phone, the app retries, we charge again. This is the pattern we use now. Zero double charges since February. The rules Every POST that moves money requires an Idempotency-Key header. No key, 400. The client generates it…
Idempotency keys for payment APIs: what we got wrong the first time
Last year we had a customer charged twice for the same EMI. Not a big amount, but the customer was right to be angry and our support team spent one full day itself on it. The root cause was not the bank, not the gateway. It was us, and the way we did idempotency keys. Sharing what we got wrong, because since then I have seen the same mistakes in two other codebases. What an idempotency key is supposed to do The…
The index that made our query slower, and other things EXPLAIN ANALYZE told me
Short version: someone added an index "because we order by that column", and the dispatcher dashboard went from 40 ms to 9 seconds for our smallest depots. The someone was me. I found out on the bike home, which is 14 km, which is enough time to stop being angry at yourself. The query SELECT id, reference, created_at FROM shipments WHERE depot_id = 42 AND status = 'pending' ORDER BY created_at DESC LIMIT 50;…
I go to the office for the bike, not for the office
Every few weeks there is a remote vs office fight in this topic. I want to give a different answer. I go to the office three days a week. Not because of the office. Because of the bike. Context. I live in Utrecht, the office is in an industrial area at the edge of the city, 14 km. I go with the bike. 35 to 40 minutes depending on wind, most of it on a separate fietspad next to a canal. It is boring. That is the…