AI summary

Why SQS can deliver the same event twice, and how an idempotent consumer keeps ClickHouse counts right with stable event IDs, ReplacingMergeTree and uniqExact.

  • Duplicates can come from the queue, the consumer or the producer, so the event needs its own ID from the source.
  • ReplacingMergeTree removes duplicates eventually, during merges. Queries have to handle the ones still there.
  • Insert deduplication covers a retry of the same block. On a second delivery, the SQS message usually arrives in a different batch.

SQS is Amazon’s message queue. A producer puts messages in. A consumer, the code on the other end, reads each message, handles it and deletes it.

Standard SQS queues, the default type, deliver every message at least once, so sometimes the consumer gets the same message twice. AWS tells you to make the consumer idempotent: handling the same message twice has the same effect as handling it once.

ClickHouse is a database built for analytics. When the consumer writes to ClickHouse, 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 ClickHouse queries count by that ID.

I took part in a team move from OpenSearch to ClickHouse. I worked on the table design, how events got into ClickHouse, the migration checks and the application’s queries. Popup view events came in large numbers, so they went through an SQS queue instead of straight to the database. This is how I’d design that path today.

Where the duplicate comes from

When a consumer receives a message, SQS hides it from other consumers for a set time, the visibility timeout. If the consumer doesn’t delete the message in that time, SQS makes it visible again.

The easiest case to picture is a write that succeeds just before the consumer dies:

One event, two rowsAn illustrative failure. Scrub through it, or press play.
  1. Receive

    The consumer gets the message. SQS hides it for the visibility timeout.

  2. Insert

    The row reaches ClickHouse.

    INSERT INTO events ...
  3. Crash

    The consumer dies before deleting the message. SQS never hears about the success.

  4. Timeout ends

    The message becomes visible again.

  5. Second delivery

    A consumer receives the same message and inserts the same event.

  6. Merge, eventually

    Two rows share one event_id until a background merge keeps only one.

A consumer 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. SQS 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 consumer can pick up the message while the first is still working.
  • The producer. If a send times out and the producer retries, the same event goes into the queue twice, as two separate messages.

FIFO queues don’t remove the problem. They drop a repeated send within five minutes, but a consumer 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 SQS gives each message. When the producer sends the same event twice, the two messages get different ones. Don’t generate the ID in the consumer either, because it would be different on the second delivery.

ReplacingMergeTree and what it doesn’t promise

ClickHouse 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 merge.

Every ClickHouse table has an engine, which decides how the table stores and merges its data. The table in the code below uses ReplacingMergeTree.

That engine removes the duplicates for you, but only during merges. The docs say the timing isn’t predictable and the engine doesn’t guarantee that duplicates are gone.

sql
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. ClickHouse splits the table into partitions, here one per month of occurred_at, and never merges 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 merge runs, your queries have to cope with the duplicates that are still there. FINAL makes ClickHouse 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, ClickHouse reads less of the table, so FINAL costs less.

For a plain count, uniqExact(event_id) counts each ID once and needs no FINAL:

sql
-- 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 ClickHouse, a materialized view is a query that runs on each inserted block and writes its result to another table. If that result is a count, it includes the duplicate, even after the source table merges the duplicate away.

Insert deduplication covers a narrower case

ClickHouse also has insert deduplication: it can skip an incoming 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 SQS message usually arrives alongside different messages, so the block is different and nothing matches.

Replicated tables 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 consumer dies in between, you get a duplicate, and you can handle those now. The other order can lose the event.

ts
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, ClickHouse collects small inserts in a buffer and writes them to disk together. Keep wait_for_async_insert at 1. With 0, ClickHouse 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 queue catch the bad ones.

Test the gap on purpose

Stop a consumer 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 SQS. I created the table above in ClickHouse 26.10 and stopped merges. Then I sent the same event in two separate inserts, each time next to a different event:

sql
SELECT count(), uniqExact(event_id) FROM events;
text
   ┌─count()─┬─uniqExact(event_id)─┐
1. │       4 │                   3 │
   └─────────┴─────────────────────┘

After OPTIMIZE TABLE events FINAL forced a merge, 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 OpenSearch and from ClickHouse, 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), no FINAL needed.
  • Sums: FINAL with filters on key columns, or LIMIT 1 BY event_id in a subquery.
  • A retry of the same insert: insert deduplication.

The same idea applies to workflows that call APIs. I wrote about retrying writes in n8n separately.

References

  1. Amazon SQS at-least-once delivery
  2. Amazon SQS visibility timeout
  3. Exactly-once processing in Amazon SQS
  4. SQS API: DeleteMessageBatch
  5. ClickHouse: ReplacingMergeTree
  6. ClickHouse: Insert deduplication on retries
  7. ClickHouse: Table partitions
  8. ClickHouse: Asynchronous inserts
  9. ClickHouse: Incremental materialized views

Written by:

Full Stack Software EngineerSamsun, Türkiye

Full Stack Software Engineer. I started with client sites at an agency in 2019, then worked on embeds, a dashboard and analytics at a startup called Popupsmart.