In MVK’s club system (MVK is Medeniyet Vizyon Kulübü, a student club at my university), members earn points as they attend events, take on tasks and get their ideas into the program. On paper it looks like simple gamification. But at the end of the road there’s a participation certificate, handed out at the end of the term and verifiable on a public page. Which means one day someone will show that certificate to an employer, and the sentence “this person really did attend this many events” had better be true.

The note I wrote to myself while drafting the plan was exactly this: the certificate’s entire value rests on the points being trustworthy, so treat them with an accountant’s rigor. In this post I want to show what that rigor turned into in practice. Grab your tea, it’s not a long one.

Points aren’t a number, they’re a ledger

The first thing that comes to mind is probably adding a puan (points) column to the uye (member) table and bumping it on every attendance. That was my first thought too. The problem is this: the day that number turns out wrong, you have no answer to the question “why?”. All you have is a number.

So instead I keep points in a table called puan_hareketi (roughly “points movement”), and it behaves like an accounting ledger:

  • Every row is a movement: +10, +40, -15 and so on.
  • A member’s points aren’t stored anywhere; they’re computed every time with SUM(miktar).
  • Every row is tied to its source: kaynak_tur (source type: attendance, task, idea, no-show, manual…) and kaynak_id. That way, on the member panel, the question “where did these 40 points come from?” always has an answer.
  • The amount is written into the row itself. Even if you raise the attendance reward from 10 to 15 tomorrow, past rows keep the rule that applied on their day; history stays correct on its own.

A stored balance means a second source of truth that’s bound to drift away from the ledger sooner or later. And once the two disagree, nobody can tell which one is right. That’s why a test looks at information_schema and checks that the uye table has no column called puan or bakiye (balance). If someone ever adds one “for performance”, the test will turn red.

“The app doesn’t delete” is an intention, not a guarantee

The backbone of the ledger is this rule: rows are never deleted or edited. At first the rule lived only in the application, at the level of “well, our code doesn’t send UPDATEs anyway”. But a single wrong db.update(...) could have quietly rewritten history. So I told myself: the app not doing it is an intention, not a guarantee.

So how do you enforce it in the database? The first idea is a CHECK constraint, but that doesn’t work. A CHECK only looks at the new version of the row; it can’t see the question “did this row exist before?”. The only thing that can reject UPDATE and DELETE is a trigger. Here’s a trimmed-down version of what’s in the migration:

CREATE FUNCTION puan_hareketi_degismez() RETURNS trigger AS $$
BEGIN
  IF coalesce(current_setting('mvk.defter_bakim', true), '') = 'acik' THEN
    IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
    RETURN NEW;
  END IF;
  RAISE EXCEPTION 'Puan defteri append-only (id=%).', OLD.id
    USING ERRCODE = '23514';
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER puan_hareketi_degismez_trg
  BEFORE UPDATE OR DELETE ON puan_hareketi
  FOR EACH ROW EXECUTE FUNCTION puan_hareketi_degismez();

There are three small details here, and each one taught me something.

First, TRUNCATE doesn’t fire row-level triggers at all. So if the protection above had been left on its own, truncate puan_hareketi would wipe the whole ledger in a single command. There’s a separate BEFORE TRUNCATE trigger for that.

Second, there’s a maintenance door: if the session has mvk.defter_bakim = 'acik' set (roughly “ledger maintenance = open”), the trigger lets things through. Without the door, test cleanup would get stuck, and manual maintenance, like a real KVKK deletion request (KVKK is Turkey’s personal data protection law), would be impossible. Application code never writes this setting. The door is opened with set_config(..., true), so it’s bound to the transaction; you can’t forget to close it. And the fact that it’s a single string is deliberate: so you can grep for it and find out who’s using the door. The true passed as the second argument to current_setting is a must too, because if the setting was never defined it returns NULL instead of throwing an error. Without it, even every INSERT would blow up.

Third, and I think the most honest one: this protection guards against application bugs, not against someone with privileged access to the database. Anyone who can drop the trigger can also change the ledger. I’m not claiming anything more than that, and I wrote it down plainly in the plan too.

There’s also a watchdog test. It temporarily drops the trigger and shows that the UPDATE really does go through. Otherwise the “UPDATE is rejected” tests could have stayed green even with no trigger at all, and I’d never have noticed.

A correction is a new row

So what if an admin hands out points by mistake? You don’t delete the row; you add a new row with the opposite sign. The example in the development seed makes this easy to see: +40, +10, -15, +15, total 50. The last row is a correction that undoes the one before it. Both stay on the panel, and the story is complete.

Manually awarded points require a reason, and that’s protected by a CHECK in the database: if kaynak_tur = 'elle' (manual), the reason can’t be empty.

This rule had a side effect I didn’t see coming. In the first design, the foreign key for the identity of the person who gave the points (veren_id) was on delete set null; the idea was “keep the movement even if the giver is deleted”. The tests caught it: set null is actually an UPDATE sent to the ledger, and the trigger rightly rejects it. So that intention could never have been reached in the first place. The right answer was more consistent: no action. Nothing in a ledger row ever changes, including “who gave it”. The general rule I took away from this: on append-only tables with CHECKs, think about foreign key behavior together with the triggers and CHECKs.

For the same reason, a member who has ledger entries can’t be hard-deleted without opening the maintenance door; cascading deletes get caught by the trigger as well. Besides, the normal flow isn’t deletion but anonymization: when an account is closed, the personal fields are cleared, and the ledger stays with an anonymous reference.

The same attendance shouldn’t count twice

The attendance system can also work offline. The price of that is this: sync might resend the same batch, and two requests might even arrive at the same moment. The classic “ask first, then write” (select, and insert if nothing’s there) is two separate queries here, with a window in between. Both requests get the answer “not there”, both write, and you end up with double points.

The fix is a single partial unique index and a single statement:

CREATE UNIQUE INDEX puan_hareketi_kaynak_benzersiz
  ON puan_hareketi (uye_id, kaynak_tur, kaynak_id)
  WHERE kaynak_id IS NOT NULL;

INSERT INTO puan_hareketi (uye_id, miktar, kaynak_tur, kaynak_id)
VALUES ($1, $2, 'yoklama', $3)
ON CONFLICT (uye_id, kaynak_tur, kaynak_id) WHERE kaynak_id IS NOT NULL
DO NOTHING
RETURNING id;

In the code this is written with Drizzle, but the SQL it produces is essentially this. If a row comes back, we wrote it; if it’s empty, it was already there. Atomic, one step.

Why partial? Because manually awarded points have no kaynak_id; it’s NULL. And the “correction = new row” rule requires that the same member can have more than one manual row. Since Postgres treats NULLs as distinct from each other for uniqueness, an unconditional constraint was working today too, but only by accident. If someone added NULLS NOT DISTINCT one day, every member would be stuck with a single correction for life, and it would happen silently. That’s why I wrote the predicate out explicitly. One more practical detail: if your ON CONFLICT target points at a partial index, you have to give the predicate too; if you don’t, Postgres can’t find a matching constraint and blows up with error 42P10.

Thanks to this, there was no need for a “processed” flag either. A flag would have been yet another source of truth that could drift away from the ledger. When the points job was tried live, the first run wrote 3 rows, and the second run wrote 0 and skipped all 3. Exactly the behavior I wanted.

Since manual points fall outside this index, they needed protection from somewhere else: the manual points form clears itself after a successful submit. A form that stayed filled in could have gotten the same row written to the append-only ledger a second time.

No data isn’t the same as no attendance

This part is interesting, because the heart of the problem isn’t code, it’s a single sentence.

Signing up and then not showing up without telling anyone comes with a penalty: -15. At first glance the rule is simple: everyone registered for the event who isn’t marked “attended” in the check-in gets the penalty. But think about this: what happens if the volunteer at the door never even opened the check-in screen? Everyone registered for that event shows up as “not marked”, and every single one of them silently gets a -15. And because the ledger is append-only, fixing that means writing new rows one by one.

This rule wasn’t written down anywhere, and its absence was dangerous. So now the penalty has to pass through two gates:

  1. The event gate: there must be at least one check-in row for that event. If there are none, you can’t answer “who didn’t come?”; you simply don’t have the data, and that’s that.
  2. The person gate: did they have a seat, did they say “I can’t make it”, did they get their seat early enough? Penalizing someone who got bumped up from the waitlist at the last minute would be unfair.

The same logic later carried over to badges too: an event that never had a check-in neither breaks nor extends a “consecutive attendance” streak; it just drops out of the sequence. There’s also a symmetry rule: a member who can’t earn points (not yet verified) doesn’t get penalties written either. Otherwise they’d drop from zero into the negatives, and the only way to fix that would be to write a positive row by hand.

Looking back

The most important thing this ledger left me with is the difference between writing a rule down and enforcing it. Saying “never deleted” is an intention; the trigger, the partial index and the single-statement insert are what that intention looks like at the database level. And each of them has a watchdog test, because a green test on its own doesn’t prove the protection actually works.

I also learned this: in an append-only system mistakes are expensive, because you can’t undo them, you can only write on top of them. That’s why the real attention goes to the gates before the write. “No data isn’t the same as no attendance” looks like a small sentence, but it keeps a single forgotten check-in from wrecking the points of everyone at an event.

So one day, when you’re about to add a “balance” column to a table, stop for a minute and ask yourself: when this number turns out wrong, where am I going to find out why?