Same id twice
trade_router, my first serious attempt at a trading system, and the one question I kept coming back to.
I had a Telegram bot that relayed trade calls, and I wanted something on the other end that would read a call and actually place the trade on Solana, through GMGN's trading API. That's all trade_router was supposed to be: a webhook, a queue and a wallet. It was also the first thing I'd ever built that spends money by itself, and for the first two weeks I kept coming back to one question. What happens if the same order shows up twice?
It will show up twice. A chat message can get forwarded twice. I wanted the relay to retry when the router was slow to answer, and a POST that times out might have arrived anyway. If any of those turns into a second buy, I've spent the money twice. I also wanted the relay to stay as dumb as possible, so it holds no keys and talks to the router with one POST signed by a shared HMAC secret. Anything that can sign a transaction lives in the router.
My first answer was to make the id a property of the message. I had the relay derive it from where the call came from:
id = uuid_v5(RELAY_NAMESPACE, chat_id + ":" + message_id)
A version 5 UUID is a SHA-1 hash of a namespace and a name (RFC 9562, §5.5), so every retry of the same message carries the same id, and the router answers a repeat with {"status": "duplicate"} and does nothing else.
That first night I built the router in Python with a queue in SQLite. The next evening I rewrote it in TypeScript on Fastify, BullMQ and Prisma, and while I was at it I stopped handing trades to GMGN and started building swaps through Jupiter and sending them to the network myself. Then I spent most of a week getting it deployed and putting logins in front of it.
In the middle of that week I went back to the duplicate check, because I'd written it as a read followed by a write. Look the id up, and if it isn't there, insert it. Anything that reads and then writes has a gap between the two, and two copies of one POST arriving close together can both fit through it. So I put an atomic reservation in front of everything:
// both copies race to create the key, and only one can
const ok = await redis.set(`webhook:idem:${id}`, '1', 'PX', ttlMs, 'NX');
if (ok !== 'OK') throw new DuplicateWebhook(id);
If Redis can't answer, the router turns the webhook away. I added a timestamp header at the same time, and the router rejects a request when the header falls outside a small window or disagrees with the timestamp inside the signed body, so nobody can capture a request and play it back later.
At the end of the second week I wanted the router to run a buy and its sell on its own, without the relay. I added presets for each side, with a slippage cap, an anti-MEV fee and a maximum size, and a plan that ties a buy preset to a sell preset for one token. A plan is a status and two job ids, and I derived both ids from the plan's own id:
type PlanStatus =
| 'draft'
| 'buy_enqueued'
| 'buy_succeeded'
| 'sell_enqueued'
| 'completed'
| 'failed';
async function onBuyLanded(plan: Plan) {
if (plan.status === 'sell_enqueued' || plan.status === 'completed') return;
await enqueueTrade({ id: `${plan.id}:sell`, side: 'sell', mint: plan.mint, ...plan.sellPreset });
await setStatus(plan.id, 'sell_enqueued');
}
It's the same answer a third time. Name each step after the thing it belongs to, and asking for it twice can only produce the same name, which runs into the same duplicate check as every relay call.
The ids only cover getting in. A call gets accepted once, and a plan asks for one sell. Once a job is in the queue, the queue has retries of its own, and the ids say nothing about those.
The plan didn't know anything about price yet. It bought, and the moment the buy landed it queued the sell, which as a trading strategy mostly pays the fees twice. I wanted every step to have exactly one name before I let any of it get clever.