At KIS Academics we run a loyalty program for tutors. Teach more hours, overall or within a week, a month or a year, and you unlock achievements. And the rewards aren’t badges, they’re real money.
That one detail shaped the whole system. If a badge shows up twice, that’s a funny bug. If a payout goes out twice, that’s a very unfunny conversation. So everything here is built around one assumption: every job can run twice, run at the same time on two servers, or die halfway through.
Heads up: the code here is simplified and names are changed. Real thresholds, reward amounts and eligibility rules stay private, otherwise this post becomes a guide to farming rewards.
If you haven’t read it, I wrote about how job queues work under the hood before this. It helps, but you don’t need it.
it didn’t start like this
I didn’t start with that assumption. I learned it the hard way.
The first version was the obvious one: a worker picks up an event, reads the tutor’s progress, adds the new hours, saves it, checks achievements and queues a reward for each one that’s met. It worked in testing, so it shipped. In production it had a few problems hiding in plain sight.
The handler wasn’t awaited. This is what the rewards worker looked like:
await jobClient.worker(rewardsQueue, async (data) => {
this.handleReward(data.rewardId); // no await
});
The job function returned immediately, so BullMQ marked every job as completed, while the actual payout ran in the background. The events worker had a cousin of this bug: it wrapped everything in a try/catch that only logged the error. Either way, every job looked successful. A payout that failed never failed its job, so it was never retried, and the dashboard was all green.
That one didn’t hurt anyone directly, it just made everything else invisible.
Multiple workers could pick up the same work. The server runs as more than one instance, and each instance starts its own worker. Nothing stopped two of them from working on the same tutor at the same time:
- the event ids were random, so the same charge could be stored, and queued, more than once
- the progress update was read, add, write, with no transaction and no lock
- “has this tutor already earned this achievement?” was a plain read, and nothing in the database enforced one reward per achievement
- the payout had no idempotency key
So two workers could both read the tutor’s progress, both see a milestone crossed, both create a reward and both pay it. That’s exactly what happened: 2 tutors got paid twice for the same milestone.
The fix wasn’t one patch, it was the rest of this post: ids derived from the charge, one transaction per event, row locks, unique keys, idempotent payouts, every handler awaited, and errors thrown so BullMQ actually retries. Plus audit scripts, because I wanted to know there weren’t more cases like those two, not hope.
the flow
lesson paid ──▶ store event (same db transaction)
│
▼ after commit
events queue ──▶ worker: progress + rewards (one db transaction)
│
▼ after commit
rewards queue ──▶ worker: payout
Two queues, two workers, and the database in the middle being the source of truth. Redis only carries “go look at this id”. Every job payload is just an id; the real data lives in MySQL.
events: one per real thing that happened
Everything starts when a lesson gets paid for. That’s the event. The first problem: the same real-world thing can be reported more than once. A webhook gets retried, a backfill runs, a reconciliation job notices something. If each one creates a new event, a tutor’s hours get counted twice.
So the event id isn’t random. It’s derived from what happened:
const eventIdFor = {
"lesson.paid": (data) => `lesson.paid:${data.chargeId}`,
};
Same charge, same id. Storing it is create-and-catch instead of find-then-create, because two emits at the same moment would both pass a “does it exist?” check:
try {
await db.events.create({ data: { id, type, data, status: "pending" } });
return "created";
} catch (err) {
if (isUniqueViolation(err)) return "exists"; // already have it, fine
throw err;
}
no paid lesson without its event
The next problem: marking a lesson paid and queueing its event are two different systems. If the database write succeeds and Redis is down, the lesson is paid and the tutor never gets credit. If you queue first and the database write fails, you’ve queued an event for a payment that didn’t happen.
The fix is the outbox pattern. The event row is written in the same transaction that marks the lesson paid. Either both commit or neither does. Only after the commit does the event go on the queue:
const eventId = await db.transaction(async (tx) => {
await tx.charges.update({ where: { id }, data: { paid: true } });
return loyalty.emit("lesson.paid", data, { repository: tx, queue: false });
});
await loyalty.queueEvent("lesson.paid", eventId); // after commit
If queueing fails now, nothing is lost. The event sits in the database as pending, and a daily sweep picks up anything still pending and queues it again.
The queue call is also time-boxed to a few seconds. When Redis is down, the BullMQ client doesn’t fail, it keeps reconnecting and waiting, and everything after it in the request would wait too. Since a lost queue call is now harmless, it’s better to give up quickly, post to Slack and let the sweep handle it. Same idea for the database side: the event transaction has a max wait and a timeout, so a stuck lock fails the job (and it retries) instead of hanging the worker.
One more thing this fixed: whether a lesson counts for the program is decided at the moment it’s paid. Prices change over time, so deciding it later (in a backfill, say) would use whatever the price is by then, not what it was.
the bullmq bits
await queue.add(type, { id: eventId }, {
jobId: eventId.replace(/:/g, "-"),
attempts: 3,
backoff: { type: "exponential", delay: 2000 },
removeOnComplete: true,
removeOnFail: 100,
});
jobIdis the event id, so the same event can’t be in the queue twice at the same time. BullMQ ignores anaddwith an id that’s already queued.- The
replaceis there because BullMQ 5.60+ rejects custom job ids containing:(“Custom Id cannot contain :”). We were on an older version that accepted it, and^5.xwould’ve pulled in the breaking one on the next install. The payload carries the real id. attempts+backoffretry a failed event. That’s only safe because processing is idempotent, more on that below.removeOnFail: 100keeps the last 100 failed jobs around to look at.
The events queue also has a global concurrency of 1, across every server instance:
await queue.setGlobalConcurrency(1);
Processing is already correct with concurrency (row locks, coming up), but parallel events for the same tutor just fight over locks, and at our volume there’s nothing to gain. One at a time is simpler. The rewards queue has no limit; each payout is independent.
And one small thing that kept my Slack alerts sane: the worker’s failed event fires on every attempt. I only alert when job.attemptsMade reaches job.opts.attempts, so a retry that succeeds stays quiet.
storing progress
Progress is one row per tutor per event type, with the numbers in a JSON column:
interface LessonPaidProgress {
version: 1;
// all time
totalHours: number;
totalAmount: number;
totalCount: number;
// current week, month and year
weekStart: Date;
hoursThisWeek: number;
amountThisWeek: number;
countThisWeek: number;
// ...same for month and year
}
All-time totals plus a window for the current week, month and year. When an event from a newer week comes in, the week window starts over. The version field is there so the shape can change later without guessing what old rows look like.
Each event type has a handler with one pure function: take the current progress and an event, return the new progress. No database, no side effects. That makes it easy to test, and as you’ll see, easy to replay.
updating progress exactly once
This is the core of it. Processing one event looks like this:
await db.transaction(async (tx) => {
// 1. claim the event: pending -> processed
if (!(await tx.claimEvent(event.id))) return "already_processed";
// 2. lock the tutor's progress row
const current = await tx.getProgress(type, tutorId, { forUpdate: true });
// 3. compute and save new progress
const updated = handler.updateProgress(event, current);
await tx.saveProgress(type, tutorId, updated);
// 4. create rewards for any achievement it now meets
for (const achievement of await tx.achievementsNotYetEarned(tutorId, type)) {
if (meets(achievement.condition, updated)) {
rewards.push(await tx.createReward(achievement, tutorId, "pending"));
}
}
});
Claiming the event, updating progress and creating rewards all commit together, or not at all. If anything throws, everything rolls back, the job fails and BullMQ retries it from a clean state. If the job runs again after a successful commit, the claim fails and it’s a no-op.
claimEvent and the progress read are SELECT ... FOR UPDATE. That row lock makes two events for the same tutor run one after the other instead of both reading 10 hours and both writing 12. Same race condition from my last post, now in MySQL.
Now the part that took me the longest. These locking reads are raw SQL, on purpose:
const rows = await tx.$queryRaw`
SELECT status FROM events WHERE id = ${id} FOR UPDATE`;
if (rows[0]?.status !== "pending") return false;
await tx.$executeRaw`UPDATE events SET status = 'processed' WHERE id = ${id}`;
In MySQL (InnoDB), a transaction’s snapshot is taken at its first plain SELECT. A locking read doesn’t start it. If the first thing the transaction does is a plain read (which is what an ORM update() might do under the hood), the snapshot is fixed before we get the lock. We then wait for the other worker to commit, get the lock, and keep reading the old snapshot, without the other worker’s changes. Taking the lock first means everything after it sees what the previous lock holder committed.
events don’t arrive in order
I assumed events would get processed in the order they happened. They don’t. A failed event retries after its backoff, behind the events queued after it. The daily sweep picks up a stuck event days later.
With windows, that’s a problem. Say the stored window is week 10, and a late event from week 9 shows up. The naive code sees “different week” and resets the window to week 9, throwing away week 10’s hours. Then the next week 10 event resets it again, back to zero.
So adding an event to a window has three cases:
const addToWindow = (startOf, event, window) => {
const eventPeriod = startOf(event.createdAt).getTime();
const windowPeriod = startOf(window.start).getTime();
if (eventPeriod > windowPeriod) return newWindow(event); // newer period
if (eventPeriod < windowPeriod) return window; // older, closed period: leave it
return addTo(window, event); // same period
};
A late event still counts in the all-time totals; it just leaves the window alone. That way, whatever order events come in, the progress ends up the same as processing them in date order. There’s a trade-off: a late event can’t push its own, already closed week over a weekly milestone. Fixing that needs per-period history, and we don’t need that yet.
timezones, of course
Week and month windows used date-fns’ startOfWeek and friends, which use the process’s local timezone. The server runs in UTC, so everything looked fine. Then I ran the audit script (below) on my laptop in IST, and it flagged every single tutor as broken. The repair script would’ve written window starts that the server then read as a different week.
The fix: tiny UTC versions of those helpers, used everywhere:
const startOfUtcWeek = (d: Date) =>
new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - d.getUTCDay()));
Lesson learned: if a script can run on someone’s laptop, “the server is in UTC” isn’t a guarantee.
conditional achievements
Achievements are rows in the database, not code. Each one has a condition, written as an expression over the progress fields:
totalHours >= 100
hoursThisMonth >= 20 && countThisMonth >= 8
(made-up numbers, obviously)
The conditions are evaluated with jexl, an expression language that runs against a context object, here the tutor’s updated progress:
import jexl from "jexl";
const meets = (condition: string, progress: object): boolean =>
jexl.evalSync(condition, progress);
It only reads the context you give it, no access to anything else, which is what you want when conditions live in the database. Adding a new achievement is inserting a row. No deploy.
The query for achievements only returns active ones the tutor hasn’t already earned, so each event checks just the remaining few. The same condition string also powers the progress bars in the app: parse out the field and the target number, divide.
rewards, exactly once
Even with all of the above, there’s one last guard in the schema:
model Rewards {
// ...
@@unique([tutorId, achievementId])
}
One reward per tutor per achievement, no matter what bug shows up in the code above it. Achievements aren’t recurring, so this holds. If that ever changes, the key needs a period column.
Rewards are created as pending inside the event transaction, and queued for payout after the commit. Queueing after commit never throws: the event is already marked processed, so a retry would skip it. A reward that fails to queue just stays pending, and another daily sweep queues it again. If one stays pending for more than 2 days, it posts to Slack.
The payout itself is where the money moves, so it gets the most paranoia:
- An idempotency key per reward on the payment API call. A retry of the same call returns the original result instead of paying again.
- Idempotency keys expire (24 hours with Stripe), and a sweep can retry days later. So before paying, it looks up whether a payment for this reward already exists, and if so, just records it.
- Where it’s paying to gets saved on the reward before paying, so that lookup still finds the payment if the tutor’s payout account changes in between.
- Never reverse automatically. If the payment went through but saving that fact to the database failed, the retry finds the payment and only redoes the database write. Reversing would make the retry record a reversed payment as the real one.
nothing silently dropped
Background jobs fail quietly. Nobody notices a loyalty event that never got processed until a tutor asks why their hours are wrong. So there are three daily crons:
- pending events: queue again any event that was stored but never processed
- pending rewards: queue again any reward that never got paid, alert if it’s stuck
- missing events: report-only, finds paid lessons that should’ve produced an event but didn’t (e.g. marked paid through some other path)
checking that it all holds
This is the part I’m happiest with. Since events are the record of what was counted, progress can always be rebuilt: replay a tutor’s processed events oldest first through the same updateProgress function the live flow uses. If the result doesn’t match what’s stored, progress has drifted.
That gives me a few admin scripts:
- audit (read-only): duplicate rewards, progress that doesn’t match its events, stuck work, and what pending events would pay out
- recompute progress: rebuild a tutor’s progress by replaying events, inside a transaction holding the same row lock, so it can’t interleave with live processing
- fix duplicates: for events and rewards left over from the first version. Until it merges them, a reward whose tutor and achievement have another row is refused at payout, so old duplicates can never be paid again
All of them are dry run by default. You have to pass --execute to actually write anything. When the script touches money, I want to read what it would do first.
And the tests run against a real MySQL database, not an in-memory fake. The guarantees here are row locks, transactions and unique keys. A fake repository would happily pass every test and prove none of them.
what i’d tell past me
- Await your handlers. A job function that returns before its work is done is a job that always succeeds. Turn on
@typescript-eslint/no-floating-promises. - Don’t swallow errors in a worker. Log them, then throw. A caught error is a retry that never happens.
- Assume every job runs twice. Then make that boring: a second run should be a no-op.
- Derive ids from what happened. One real thing, one id, everywhere.
- Write the event with the thing that caused it. Outbox first, queue after commit.
- The queue is a hint, the database is the truth. Redis says “look at this id”, MySQL decides what that means.
- Keep the raw events. Being able to replay them made every bug fixable instead of permanent.
- Dry run by default for anything that touches money.
- Use UTC everywhere. Then do it again for the scripts you run locally.
Learning how queues work under the hood made all of this much easier to reason about. Once you know a job can be picked up, crash, and come back, you stop trusting “it’ll only run once” and start building for “it’ll run at least once”.