Published on

Ingest That Can Be Replayed

Authors

If you take a product feed which sends a message when a price changes. 10 o'clock product 1042 drops from 125,- to 99,- kr. The message has version 7. 10:05 and the price goes up to 119 kr. Which has version 8.

Both are saved in the import. Then the 10 o'clock message arrives again and suddenly the price is back at 99 kr (version 7). There was no error logged, since the import just saved whatever came last. It completely ignored that this old version is not the latest version. An error is only logged when there is some actual validation logic or an exception thrown.

Messages come more than once

A message can come more than once. It is a common scenario. A queue can deliver the same message twice by accident. For example when the import saves the price but crashes before it tells the queue it is done. Then the second copy of that message arrives after a newer message.

And sometimes I do it myself. The import was down for an hour, so I run the files from that hour again, starting a little earlier to be sure nothing is missed. So I assume every message can arrive twice, and in any order.

A key and a version

The key says which product the message belongs to. The key is the product ID in this sample.

The version dictates how new the message is. It has to come from the source system, since the source knows the order the changes happened in. The time an import received a message does not work, because the order could be wrong.

A simple rule: "Only save if the version is higher than the one I have."

StoredIncomingResult
nothingv7, 99 krSaved
v7, 99 krv8, 119 krSaved
v8, 119 krv8, 119 krDuplicate
v8, 119 krv7, 99 krOld
v8, 119 krv9, deletedSaved
v9, deletedv8, 119 krOld

Deleted products

Example: product 1042 is removed. That message has version 9. Here we delete the row in the database when a delete message is received. Then I run some files again, and the version 8 message comes through. The import cannot find product 1042, so it creates it. Now we suddenly have the product again.

Deleting a row also deletes the version. So better not to delete the row. Mark it as deleted and keep that version. The shop shows products that are not marked. So if the old version 8 message arrives again, then it knows it should not do anything.

If the product is put back in the shop later, the source sends version 10, and it is saved as normal.

The code

public sealed record ProductMessage(
    string ProductId,
    long Version, // set by the source, never by the import
    decimal? Price,
    bool Deleted);

public sealed record StoredProduct(long Version, decimal? Price, bool Deleted);

public enum Result { Saved, Duplicate, Old }

public sealed class ProductStore
{
    readonly Dictionary<string, StoredProduct> _products = new();

    public Result Apply(ProductMessage m)
    {
        if (_products.TryGetValue(m.ProductId, out var stored))
        {
            if (m.Version == stored.Version) return Result.Duplicate;
            if (m.Version < stored.Version) return Result.Old;
        }

        // A delete keeps the row and the version. It only marks the product.
        _products[m.ProductId] = new StoredProduct(m.Version, m.Price, m.Deleted);
        return Result.Saved;
    }

    public IEnumerable<string> ForSale() =>
        _products.Where(p => !p.Value.Deleted).Select(p => p.Key);
}

Delete also goes through the check, so we prevent an old delete from removing a newer product.

In this sample we keep the products in memory. This is just to keep it simple. When we are dealing with a real database, I would put the check in the update itself: UPDATE Products SET ... WHERE ProductId = @id AND Version < @version. And if the product is not there yet, then it is inserted instead.

But why don't we just read the version first, and then we do the compare in C#? - It is because two workers can be running at the same time. One worker could get version 8 and the other one version 9. They would both read 7 and both of them think they have the newest version.

When we do the check in the update query, then it is the database that does the comparison and we avoid this bad scenario.

Final thought

I sometimes still write imports which might overwrite what is meant to be there. It will work fine in tests, but tests mostly just send a message once in the right order. It does not replicate the async paradigm.