Two stores, one truth: building a reconciliation worker that keeps Druid and SQL in sync without hurting either
If you stream the same events into two different stores, they will drift apart. Not "might". Will.
On a national-scale vehicle telemetry platform I work on, live GPS data flows through Kafka into Apache Druid, which powers real-time alerting and analytics. A relational SQL database sits next to it for reporting and the parts of the product that want normal tables and joins. Both are supposed to tell the same story.
This post is about the worker I built to make sure they actually do: a daily job that finds gaps, replays the missing data in throttled chunks, proves the fix worked, and never runs twice at the same time. The code below is a simplified version of the approach with example table and column names, in C# and SQL Server, but the design applies to any pair of stores.
Why two stores drift
Every one of these will happen eventually in a streaming system:
- No shared transaction. Writing an event to Druid and to SQL are two separate operations. If one succeeds and the other fails, nothing rolls the first one back.
- At-least-once delivery. Kafka consumers can see the same message twice after a rebalance or restart. One sink deduplicates, the other doesn't, and now the counts disagree.
- Outages on one side. If the SQL writer is down for twenty minutes and the topic's retention or the consumer's offset handling isn't perfect, that window is just gone from one store.
- Late data. Devices that lose signal buffer readings and send them later. Druid accepts late events into old time intervals. A one-time copy job that already ran won't see them.
You can reduce each of these, but you can't make the risk zero. So the honest design is: accept that drift happens, detect it cheaply, repair it safely, and prove the repair.
Design goals
Before writing code, I wrote down what the worker must never do and what it must always do:
- Never hurt the live system. Druid is serving real-time alerts. A background job that floods it with heavy queries is worse than the drift it fixes.
- Be idempotent. Running the same repair twice must leave the data exactly as running it once.
- Be resumable. If the job dies halfway, the next run continues instead of starting over.
- Prove the result. "I wrote some rows" isn't success. Success is "the two stores now agree for this window", verified after the write.
- Run exactly once at a time. Two copies running concurrently would double the load and race each other's writes.
Everything below exists to satisfy one of those five rules.
The shape of the worker
For each day in the lookback window: split the day into 4-hour chunks. For each chunk not already verified: compare Druid vs SQL (cheap). If they match: mark verified, continue. Replay the chunk from Druid into SQL (throttled, idempotent). Verify again, retry with backoff if still different. Record the outcome.
Three details in that loop carry most of the weight: the chunk size, the comparison, and the lookback window.
Why chunks, and why 4 hours
Reconciling a whole day in one query means one huge Druid scan, one huge result set in memory, and one huge write to SQL. If anything fails, the whole day fails.
We used 4-hour chunks. The trade-off is simple: small enough that a chunk's Druid query and SQL write finish in a predictable time and memory footprint, large enough that a day is 6 round trips instead of hundreds. If a chunk fails, you retry 4 hours of data, not 24.
Pick yours by measuring how long one chunk takes under real load, not by guessing.
Compare cheap first, expensive only when needed
Most chunks will match, so the comparison has to be cheap. Start with counts per chunk:
-- Druid SQL
SELECT COUNT(*) AS cnt FROM "vehicle_telemetry" WHERE __time >= ? AND __time < ?
-- SQL Server
SELECT COUNT(*) AS cnt FROM dbo.VehicleTelemetry WHERE EventTimeUtc >= @From AND EventTimeUtc < @To;
Two traps here that will bite you:
- Rollup. If your Druid datasource has rollup enabled,
COUNT(*)counts rolled-up rows, not original events. Compare against the ingested count metric instead, usuallySUM("count"), or your counts will never match. - Time zones. Druid's
__timeis UTC. If the SQL side stores local time, every chunk boundary is shifted and you'll "find" gaps that don't exist. Store UTC on both sides and compare UTC windows.
Only when counts differ do you need anything more expensive, like comparing per device or per key to find exactly which rows are missing.
Look back further than one day
Because late data lands in old intervals, a job that only checks "yesterday" will miss it. Re-check a rolling window of several days, and skip chunks that are already verified using a checkpoint table, so the extra lookback costs almost nothing when there's no drift.
Not hurting Druid: throttling and query priority
The replay query is the expensive part, and it hits the same cluster that serves live alerts. Two protections:
- Tell Druid this query is low priority. Druid's query context has a priority setting. Higher values win when the cluster is busy, so background work should go below the default of 0:
var request = new {
query = @"SELECT __time, ""device_id"", ""lat"", ""lon"", ""speed"" FROM ""vehicle_telemetry"" WHERE __time >= ? AND __time < ?",
parameters = new object[] {
new { type = "TIMESTAMP", value = chunk.FromUtc.ToString("yyyy-MM-dd HH:mm:ss") },
new { type = "TIMESTAMP", value = chunk.ToUtc.ToString("yyyy-MM-dd HH:mm:ss") }
},
context = new { priority = -10, timeout = 120_000 },
resultFormat = "object"
};
using var response = await _druid.PostAsJsonAsync("/druid/v2/sql/", request, ct);
response.EnsureSuccessStatusCode();
- Throttle the replay. Write in fixed-size batches with a pause between them, and back off when the database is slow. A simple version:
foreach (var batch in rows.Chunk(5_000))
{
var sw = Stopwatch.StartNew();
await UpsertBatchAsync(batch, ct);
// If SQL is getting slower, give it more room
var pause = sw.Elapsed > TimeSpan.FromSeconds(2) ? TimeSpan.FromSeconds(5) : TimeSpan.FromMilliseconds(500);
await Task.Delay(pause, ct);
}
It's deliberately boring. The goal isn't to repair as fast as possible. It's to repair without anyone noticing the repair is running. Schedule it off-peak too.
Idempotent writes: staging table plus MERGE
Replaying a chunk will re-send rows that already exist in SQL. That has to be harmless. The pattern that works well on SQL Server is: bulk copy the batch into a staging table, then merge on the natural key.
// #TelemetryStaging is created earlier on the same connection, with the same columns as the target
using (var bulk = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, tx))
{
bulk.DestinationTableName = "#TelemetryStaging";
await bulk.WriteToServerAsync(batchTable, ct);
}
MERGE dbo.VehicleTelemetry WITH (HOLDLOCK) AS target
USING #TelemetryStaging AS src
ON target.DeviceId = src.DeviceId AND target.EventTimeUtc = src.EventTimeUtc
WHEN NOT MATCHED BY TARGET THEN
INSERT (DeviceId, EventTimeUtc, Lat, Lon, Speed)
VALUES (src.DeviceId, src.EventTimeUtc, src.Lat, src.Lon, src.Speed);
A few notes on this pattern:
- The natural key (here device plus event time) needs a unique index, both for MERGE performance and as the final guard against duplicates.
HOLDLOCKmatters. Without it, MERGE can race with the live writer and insert duplicates under concurrency.- Only insert what's missing. Updating existing rows during a repair is a different, riskier decision, and you should make it on purpose, not by accident.
On PostgreSQL, the same idea is INSERT ... ON CONFLICT (device_id, event_time) DO NOTHING.
Verify, then verify again
After the write, the worker runs the same cheap comparison for that chunk. If the counts match, the chunk is marked verified. If not, it retries with exponential backoff:
for (var attempt = 1; attempt <= 3; attempt++)
{
await ReplayChunkAsync(chunk, ct);
var (druid, sql) = await CompareAsync(chunk, ct);
if (druid == sql)
{
await MarkVerifiedAsync(chunk, druid, ct);
return;
}
if (attempt < 3) await Task.Delay(TimeSpan.FromMinutes(Math.Pow(2, attempt)), ct);
}
await MarkFailedAsync(chunk, ct); // and alert a human
Why would counts still differ right after a successful write? Usually because the source is still moving: late events are landing in that same Druid interval while you compare. Waiting and re-checking resolves that case.
If a chunk still disagrees after the retries, it's a real problem, and a human should look at it. The worker's job is to fix the routine cases and escalate the weird ones, not to loop forever.
Exactly one runner: a lock with a lease
If a deploy, a scheduler hiccup or an operator starts a second copy, you get double load and racing writes. A database row works well as a distributed lock, as long as it expires. Otherwise a crashed worker holds the lock forever.
CREATE TABLE dbo.JobLease (
JobName sysname PRIMARY KEY,
Owner nvarchar(100) NULL,
ExpiresAtUtc datetime2 NOT NULL
);
-- Seed once:
INSERT dbo.JobLease (JobName, Owner, ExpiresAtUtc) VALUES ('druid-sql-resync', NULL, '2000-01-01');
-- Acquire (or renew) the lease. Succeeds only if it's free, expired, or already ours.
UPDATE dbo.JobLease
SET Owner = @Me, ExpiresAtUtc = DATEADD(MINUTE, 15, SYSUTCDATETIME())
WHERE JobName = 'druid-sql-resync'
AND (ExpiresAtUtc < SYSUTCDATETIME() OR Owner = @Me);
-- @@ROWCOUNT = 1 means we hold the lease
The worker renews the lease between chunks, well before it expires. If the process dies, the lease simply runs out and the next run takes over. Because chunks are checkpointed, it continues where the dead one stopped.
One more rule: check that you still hold the lease before each chunk's write, not only at the start. If your process stalled for longer than the lease (a long GC pause, a frozen VM), another runner may now own the job, and you should stop.
Observability: make drift visible
The checkpoint table doubles as the report. One row per chunk with the window, Druid count, SQL count, rows replayed, attempts and final status gives you:
- a daily answer to "do the two stores agree?" that doesn't require anyone to run queries by hand,
- a trend: if replays suddenly grow, something upstream broke, and the reconciliation numbers tell you before users do,
- a clear list of failed chunks for a human to investigate.
That last point changes the conversation. Instead of "the report looks wrong, can someone check?", it becomes "this 4-hour chunk failed verification, here's the count difference".
What I'd tell anyone building one
- Assume drift and design for repair. Trying to make two independent writes perfectly consistent is a losing fight. Detecting and repairing is a winnable one.
- Protect the live system first. Low query priority, small batches, pauses, off-peak scheduling. A repair job that causes an incident has failed.
- Idempotency is the whole game. If replaying is safe, retries are safe, and if retries are safe, the job can be simple.
- Verify after you write. Writing rows isn't success. Agreement is success.
- Locks need leases, and leases need re-checking. A lock that can't expire will eventually stop your job forever.
- Watch the trend, not just the failures. How much the worker repairs each day is one of the best health signals your pipeline has.
None of the pieces here is exotic: counts, chunks, a MERGE and a lease row. The value comes from putting them together so the job is safe to run every day, safe to kill at any moment, and honest about whether it worked.
Comments
No comments yet. Start the discussion.