AI summary
Why SQSAmazon's hosted message queue. One part of your system puts messages in, and another part reads them out later. can deliver the same event twice, and how an idempotentHandling the same message twice has the same effect as handling it once. consumerThe code that reads messages from the queue, handles them and deletes them. keeps ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows. counts right with stable event IDs, ReplacingMergeTreeA kind of ClickHouse table that removes duplicate rows, but only later, when it combines the table's data in the background. and uniqExactA ClickHouse function that counts how many different values a column has, exactly..
- Duplicates can come from the queue, the consumerThe code that reads messages from the queue, handles them and deletes them. or the producerThe code that sends messages to the queue., so the event needs its own ID from the source.
- ReplacingMergeTreeA kind of ClickHouse table that removes duplicate rows, but only later, when it combines the table's data in the background. removes duplicates eventually, during merges. Queries have to handle the ones still there.
- Insert deduplication covers a retry of the same blockThe rows ClickHouse receives and writes in one go. A small insert is usually one block.. On a second delivery, the SQSAmazon's hosted message queue. One part of your system puts messages in, and another part reads them out later. message usually arrives in a different batch.
SQSAmazon's hosted message queue. One part of your system puts messages in, and another part reads them out later. is Amazon’s message queue. A producerThe code that sends messages to the queue. puts messages in. A consumerThe code that reads messages from the queue, handles them and deletes them., the code on the other end, reads each message, handles it and deletes it.
Standard SQSAmazon's hosted message queue. One part of your system puts messages in, and another part reads them out later. queues, the default type, deliver every message at least once, so sometimes the consumerThe code that reads messages from the queue, handles them and deletes them. gets the same message twice. AWS tells you to make the consumerThe code that reads messages from the queue, handles them and deletes them. idempotentHandling the same message twice has the same effect as handling it once.: handling the same message twice has the same effect as handling it once.
ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows. is a database built for analytics. When the consumerThe code that reads messages from the queue, handles them and deletes them. writes to ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows., the second delivery of a message becomes a duplicate row. The row stays in your counts until something removes it.
You can’t stop the second delivery, but you can stop it from counting twice: give every event its own ID where it’s created, and make your ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows. queries count by that ID.
I took part in a team move from OpenSearchAn open-source search and analytics database. to ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows.. I worked on the table design, how events got into ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows., the migration checks and the application’s queries. Popup view events came in large numbers, so they went through an SQSAmazon's hosted message queue. One part of your system puts messages in, and another part reads them out later. queue instead of straight to the database. This is how I’d design that path today.
Where the duplicate comes from
When a consumerThe code that reads messages from the queue, handles them and deletes them. receives a message, SQSAmazon's hosted message queue. One part of your system puts messages in, and another part reads them out later. hides it from other consumerThe code that reads messages from the queue, handles them and deletes them.s for a set time, the visibility timeout. If the consumerThe code that reads messages from the queue, handles them and deletes them. doesn’t delete the message in that time, SQSAmazon's hosted message queue. One part of your system puts messages in, and another part reads them out later. makes it visible again.
The easiest case to picture is a write that succeeds just before the consumerThe code that reads messages from the queue, handles them and deletes them. dies:
- Receive
The consumer gets the message. SQS hides it for the visibility timeout.
- Insert
The row reaches ClickHouse.
INSERT INTO events ... - Crash
The consumer dies before deleting the message. SQS never hears about the success.
- Timeout ends
The message becomes visible again.
- Second delivery
A consumer receives the same message and inserts the same event.
- Merge, eventually
Two rows share one event_id until a background merge keeps only one.
A consumerThe code that reads messages from the queue, handles them and deletes them. killed for running out of memory can also die in the gap between the insert and the delete, which is one more reason to set Node’s heap limit properly in Docker.
There are other sources too:
- The queue itself. SQSAmazon's hosted message queue. One part of your system puts messages in, and another part reads them out later. keeps each message on several servers. One of them can be unavailable when you delete, so the message may come back.
- A timeout that’s too short. The default is 30 seconds. If an insert takes longer, a second consumerThe code that reads messages from the queue, handles them and deletes them. can pick up the message while the first is still working.
- The producerThe code that sends messages to the queue.. If a send times out and the producerThe code that sends messages to the queue. retries, the same event goes into the queue twice, as two separate messages.
FIFOThe other SQS queue type. It keeps messages in order and drops a repeated send within five minutes. The default type is called standard. queues don’t remove the problem. They drop a repeated send within five minutes, but a consumerThe code that reads messages from the queue, handles them and deletes them. that crashes before deleting still gets the message again.
Give the event its own ID
Create event_id where the event happens and keep it through every retry.
Don’t reuse the MessageId that SQSAmazon's hosted message queue. One part of your system puts messages in, and another part reads them out later. gives each message. When the producerThe code that sends messages to the queue. sends the same event twice, the two messages get different ones. Don’t generate the ID in the consumerThe code that reads messages from the queue, handles them and deletes them. either, because it would be different on the second delivery.
ReplacingMergeTree and what it doesn’t promise
ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows. stores each insert on disk as a separate piece, called a part. Later it combines parts into bigger ones in the background. That step is a mergeClickHouse combining the separate pieces a table is stored in into bigger ones, in the background..
Every ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows. table has an engine, which decides how the table stores and mergeClickHouse combining the separate pieces a table is stored in into bigger ones, in the background.s its data. The table in the code below uses ReplacingMergeTree.
That engine removes the duplicates for you, but only during mergeClickHouse combining the separate pieces a table is stored in into bigger ones, in the background.s. The docs say the timing isn’t predictable and the engine doesn’t guarantee that duplicates are gone.
CREATE TABLE events
(
event_id UUID,
tenant_id UInt64,
event_type LowCardinality(String),
occurred_at DateTime64(3, 'UTC'),
payload String
)
ENGINE = ReplacingMergeTree
PARTITION BY toYYYYMM(occurred_at)
ORDER BY (tenant_id, event_type, occurred_at, event_id);ReplacingMergeTree treats rows with the same ORDER BY values as duplicates of each other. So every column there has to be identical every time the event arrives.
The same goes for the partition. ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows. splits the table into partitions, here one per month of occurred_at, and never mergeClickHouse combining the separate pieces a table is stored in into bigger ones, in the background.s parts from different partitions. So partition by when the event happened, not when you received it.
For events that never change, you don’t need a version column (the engine’s ver argument), because the duplicates are identical. Add one if a later version of an event should replace the earlier one.
Until a mergeClickHouse combining the separate pieces a table is stored in into bigger ones, in the background. runs, your queries have to cope with the duplicates that are still there. FINAL makes ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows. drop the duplicates while it reads, which is exact but costs more.
The ORDER BY columns are also the table’s key. When you filter on key columns, for example tenant_id, ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows. reads less of the table, so FINAL costs less.
For a plain count, uniqExact(event_id) counts each ID once and needs no FINAL:
-- Exact result. Filter on key columns to keep the cost down.
SELECT event_type, count()
FROM events FINAL
WHERE tenant_id = 42
GROUP BY event_type;
-- For a count, this avoids FINAL.
SELECT event_type, uniqExact(event_id)
FROM events
WHERE tenant_id = 42
GROUP BY event_type;For a sum(), remove the duplicates in a subquery first with LIMIT 1 BY event_id, which keeps one row per ID. It gives the same result as FINAL, so time both on your own data and keep the faster one.
Watch out for materialized views. In ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows., a materialized view is a query that runs on each inserted blockThe rows ClickHouse receives and writes in one go. A small insert is usually one block. and writes its result to another table. If that result is a count, it includes the duplicate, even after the source table mergeClickHouse combining the separate pieces a table is stored in into bigger ones, in the background.s the duplicate away.
Insert deduplication covers a narrower case
ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows. also has insert deduplicationA ClickHouse feature that skips an insert identical to one it has already written, so a retried insert isn't stored twice.: it can skip an incoming blockThe rows ClickHouse receives and writes in one go. A small insert is usually one block. that matches one it has already written. So it’s tempting to stop there.
But this only helps when you retry the same insert after a timeout, with the same rows in the same order. On a second delivery, the SQSAmazon's hosted message queue. One part of your system puts messages in, and another part reads them out later. message usually arrives alongside different messages, so the blockThe rows ClickHouse receives and writes in one go. A small insert is usually one block. is different and nothing matches.
Replicated tablesClickHouse tables that keep a copy of their data on several servers. Their engine names start with Replicated. do this by default. A plain ReplacingMergeTree needs the table setting non_replicated_deduplication_window above 0. I’d use it for insert retries and keep event_id for everything else.
Insert first, delete second
Delete the message only after the insert succeeds. If the consumerThe code that reads messages from the queue, handles them and deletes them. dies in between, you get a duplicate, and you can handle those now. The other order can lose the event.
const { Messages = [] } = await sqs.send(
new ReceiveMessageCommand({
QueueUrl,
MaxNumberOfMessages: 10,
WaitTimeSeconds: 20,
}),
);
if (Messages.length === 0) return;
await clickhouse.insert({
table: "events",
// toRow reads event_id from the body. It never generates one.
values: Messages.map(toRow),
format: "JSONEachRow",
clickhouse_settings: { async_insert: 1, wait_for_async_insert: 1 },
});
const { Failed = [] } = await sqs.send(
new DeleteMessageBatchCommand({
QueueUrl,
Entries: Messages.map((m, i) => ({
Id: String(i),
ReceiptHandle: m.ReceiptHandle!,
})),
}),
);
// DeleteMessageBatch can return 200 with failed entries.
if (Failed.length > 0) logger.warn({ Failed }, "delete failed, expect redelivery");With async_insert, ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows. collects small inserts in a buffer and writes them to disk together. Keep wait_for_async_insert at 1. With 0, ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows. confirms the insert as soon as the data is in the buffer, so you could delete a message whose row never reaches disk.
The sample keeps parsing short, so one malformed message would make toRow throw and fail the whole batch. In real code, parse each message on its own and let a dead-letter queueA second queue where SQS moves a message after it fails too many times, so it stops coming back. catch the bad ones.
Test the gap on purpose
Stop a consumerThe code that reads messages from the queue, handles them and deletes them. between the insert and the delete, then compare count() with uniqExact(event_id). If they differ and your reports use plain count(), your reports are wrong for a while.
You can see the difference without SQSAmazon's hosted message queue. One part of your system puts messages in, and another part reads them out later.. I created the table above in ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows. 26.10 and stopped mergeClickHouse combining the separate pieces a table is stored in into bigger ones, in the background.s. Then I sent the same event in two separate inserts, each time next to a different event:
SELECT count(), uniqExact(event_id) FROM events; ┌─count()─┬─uniqExact(event_id)─┐
1. │ 4 │ 3 │
└─────────┴─────────────────────┘After OPTIMIZE TABLE events FINAL forced a mergeClickHouse combining the separate pieces a table is stored in into bigger ones, in the background., count() dropped to 3 as well.
When I think back on the migration, I’d allow more time for running the old and new read paths side by side, the same report from OpenSearchAn open-source search and analytics database. and from ClickHouseA database built for analytics. It's fast at counting and summing over millions of rows., and comparing them. When two numbers differ, finding out why can take longer than rewriting the query.
What I’d use where
- Counting events:
uniqExact(event_id), noFINALneeded. - Sums:
FINALwith filters on key columns, orLIMIT 1 BY event_idin a subquery. - A retry of the same insert: insert deduplicationA ClickHouse feature that skips an insert identical to one it has already written, so a retried insert isn't stored twice..
The same idea applies to workflows that call APIs. I wrote about retrying writes in n8n separately.
References
- Amazon SQS at-least-once delivery
- Amazon SQS visibility timeout
- Exactly-once processing in Amazon SQS
- SQS API: DeleteMessageBatch
- ClickHouse: ReplacingMergeTree
- ClickHouse: Insert deduplication on retries
- ClickHouse: Table partitions
- ClickHouse: Asynchronous inserts
- ClickHouse: Incremental materialized views
