How to keep like_count and follower_count in sync: a trigger, app writes or a rollup job

96 cached counters in our 100-schema gallery, 2 maintained by a documented trigger. The trigger, the MySQL cascade trap, hot rows, and the drift query.

· 8 min read · drawDB team

Keep like_count in an AFTER INSERT OR DELETE trigger on the likes table, declare the column NOT NULL DEFAULT 0 with a CHECK (like_count >= 0), and run a drift query on a schedule that recounts and repairs any row that disagrees. On PostgreSQL that combination stays exact through cascades, bulk deletes and ad-hoc SQL. Move a counter to a delta table folded by a job only when one row gets so many writes that transactions queue on its lock: view counts, and likes on the occasional viral post. Incrementing from application code is the weakest of the three, because the database deletes child rows that your code never sees.

We checked how the 100 schemas in the drawDB gallery handle this. 64 of them have a column ending in _count, 186 columns in all. 96 of those, across 35 schemas, are documented as a cache of rows stored somewhere else: likes, followers, comments, members, pins. Their notes are clear about why the column exists ("counting rows per card is not survivable", the Instagram schema says of posts.like_count). They are much quieter about how the number stays right:

How the note says the count is maintainedColumns
Not stated74
On the write path, in application code11
Asynchronously: a worker, a rollup, a periodic recompute9
By a trigger (both notes say "trigger or worker" / "trigger or the same transaction")2

Three facts from the same set shape the rest of this post. 12 of the 96 count a subset rather than every child row: accepted follows, non-deleted posts, non-removed comments. 7 of them sit inside an index, so the database rewrites index entries on every increment. And in the Instagram, X, TikTok, Facebook, YouTube and Pinterest schemas, every like, reaction and follow table has ON DELETE CASCADE to the user, which is the one write path application code never runs on.

Should you store a count column at all?

Not for a number that appears once per page. SELECT count(*) FROM post_likes WHERE post_id = $1 with an index on post_id is a short index scan, and on a post with a few hundred likes it costs less than maintaining a counter. The Stack Overflow answer that ranks for this question says the same: stick to count() until you have a reason not to, because a counter serializes writes on the parent row.

Store it when the count is read in lists or sorted on. A feed of 20 cards each showing likes, comments and reposts is 60 aggregate queries or 60 subqueries per page, and the cost grows with the most popular post, not the average one. Sorting is worse: "top comments" ordered by likes cannot use an index on a number that is computed at read time. That is the line the gallery draws too. Where the notes give a reason, it is a list or a sort: "shown on every board tile", "the thread list does not aggregate on every render", "used to order the reviews shown on a book page".

How do you keep a like count in sync with a trigger?

Put the column on the parent with a floor, then let the database adjust it whenever a child row appears, disappears, or moves to a different parent:

PostgreSQL
ALTER TABLE posts
  ADD COLUMN like_count integer NOT NULL DEFAULT 0
  CONSTRAINT posts_like_count_nonneg CHECK (like_count >= 0);

CREATE FUNCTION post_likes_count() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  IF TG_OP IN ('DELETE', 'UPDATE') THEN
    UPDATE posts SET like_count = like_count - 1 WHERE id = OLD.post_id;
  END IF;
  IF TG_OP IN ('INSERT', 'UPDATE') THEN
    UPDATE posts SET like_count = like_count + 1 WHERE id = NEW.post_id;
  END IF;
  RETURN NULL;
END $$;

CREATE TRIGGER post_likes_count
AFTER INSERT OR DELETE OR UPDATE OF post_id ON post_likes
FOR EACH ROW EXECUTE FUNCTION post_likes_count();

Three details matter. like_count = like_count + 1 is evaluated against the latest committed row under the row lock, so two concurrent likes never read the same old value and lose one; a read-then-write in application code (SELECT like_count, add one, UPDATE) does. UPDATE OF post_id covers the rare move between parents, which an insert-and-delete-only trigger silently miscounts. And the CHECK turns a bug that would decrement below zero into an error you see in the logs, instead of a profile showing -3 followers.

The trigger fires only when a row is actually written. INSERT ... ON CONFLICT DO NOTHING on a double-tap does not fire it, so the composite primary key on post_likes (post_id, account_id) and the counter agree without extra code. Deleting a user fires it once per like the cascade removes: in PostgreSQL, referential actions run as ordinary deletes on the child table, and its row triggers fire. We ran the code above against PostgreSQL 16 inside a transaction, deleted an account with likes on two posts, and both counts dropped by one.

What about counts with a condition, like accepted follows?

A count of a subset has to react to the column that defines the subset. The Instagram schema's follower_count is a "count of accepted inbound follows", and a follow to a private account starts as pending. Approving it is an UPDATE, not an INSERT, so a trigger that only watches inserts and deletes never counts it:

PostgreSQL
CREATE FUNCTION follows_count() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  IF TG_OP IN ('DELETE', 'UPDATE') AND OLD.status = 'accepted' THEN
    UPDATE accounts SET follower_count = follower_count - 1 WHERE id = OLD.followee_id;
    UPDATE accounts SET following_count = following_count - 1 WHERE id = OLD.follower_id;
  END IF;
  IF TG_OP IN ('INSERT', 'UPDATE') AND NEW.status = 'accepted' THEN
    UPDATE accounts SET follower_count = follower_count + 1 WHERE id = NEW.followee_id;
    UPDATE accounts SET following_count = following_count + 1 WHERE id = NEW.follower_id;
  END IF;
  RETURN NULL;
END $$;

CREATE TRIGGER follows_count
AFTER INSERT OR DELETE OR UPDATE OF status, follower_id, followee_id ON follows
FOR EACH ROW EXECUTE FUNCTION follows_count();

The pattern generalises: subtract the old row if it was in the subset, add the new row if it is. An update that leaves the status alone subtracts one and adds one, which nets out. For a soft-deleted parent such as posts.deleted_at behind accounts.post_count, the condition is deleted_at IS NULL and the watched column is deleted_at. Write the predicate in exactly one place. If the profile page counts status = 'accepted' and the trigger counts status <> 'pending', the day someone adds a blocked status the two disagree.

Why do counters drift when the app maintains them?

Because the application only sees the writes it makes. These are the usual sources of drift, roughly in the order they show up:

  1. Read, add, write. Two requests read 41 and both write 42. Always increment in SQL.
  2. Increment after an insert that did nothing. INSERT ... ON CONFLICT DO NOTHING followed by an unconditional UPDATE ... + 1 counts a double-tap twice. Gate the update on the insert: in PostgreSQL, WITH liked AS (INSERT ... ON CONFLICT DO NOTHING RETURNING post_id) UPDATE posts SET like_count = like_count + 1 WHERE id IN (SELECT post_id FROM liked); in MySQL, check the affected-rows count.
  3. Two statements, two transactions. The like commits, the process dies, the increment never runs. Same transaction, or a trigger.
  4. Cascades. Deleting an account removes its likes, follows and comments through ON DELETE CASCADE, and no line of application code runs for those rows.
  5. Everything else. A support engineer's DELETE in a SQL console, a GDPR erasure script, a data migration, a restore of one table from a backup.

The gallery's like and follow tables make the fourth one concrete. Here is the Twitter/X schema, where likes.user_id, follows.follower_id and follows.followee_id all cascade from users, and users.follower_count, users.following_count and tweets.like_count are the counters they feed:

Twitter/X's note on following_count says it is also the number the fan-out worker uses to decide whether an author is worth pushing. A counter that drifts there changes behaviour, not just a label.

Do MySQL triggers fire on cascaded deletes?

No. The MySQL manual's restrictions page says it in one line: "Triggers are not activated by foreign key actions." The same trigger in MySQL keeps like_count right for direct inserts and deletes and goes wrong the first time a user deletes their account:

MySQL
CREATE TRIGGER post_likes_ai AFTER INSERT ON post_likes FOR EACH ROW
  UPDATE posts SET like_count = like_count + 1 WHERE id = NEW.post_id;

CREATE TRIGGER post_likes_ad AFTER DELETE ON post_likes FOR EACH ROW
  UPDATE posts SET like_count = like_count - 1 WHERE id = OLD.post_id;

We ran this on MySQL 8.4: an account with likes on two posts was deleted, the cascade removed both likes, and both posts kept counting them. The fix is to do the cascade's counter work yourself, in the same transaction, before the parent delete:

MySQL
START TRANSACTION;

UPDATE posts p
JOIN post_likes l ON l.post_id = p.id
SET p.like_count = p.like_count - 1
WHERE l.account_id = 42;

DELETE FROM accounts WHERE id = 42;

COMMIT;

The join matches each post at most once per account because (post_id, account_id) is the primary key. Repeat the statement for every counter the account's child rows feed: follower counts on the accounts they followed, comment counts on the posts they commented on. That list is the argument for the drift query below; nobody keeps it complete for long. CHECK constraints are enforced from MySQL 8.0.16, so the floor works there too.

What do you do when one row gets too hot?

Every like takes a row lock on the post until the transaction commits. That is invisible at ten likes a minute and a queue at ten thousand a second on a single post. The usual fix is to stop updating the hot row on every write. Append a delta to a narrow table instead, and fold the deltas into the counter every few seconds:

PostgreSQL
CREATE TABLE post_like_deltas (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  post_id bigint NOT NULL,
  delta smallint NOT NULL
);

WITH moved AS (
  DELETE FROM post_like_deltas
  RETURNING post_id, delta
), totals AS (
  SELECT post_id, sum(delta) AS delta FROM moved GROUP BY post_id
)
UPDATE posts p
SET like_count = p.like_count + t.delta
FROM totals t
WHERE p.id = t.post_id AND t.delta <> 0;

The trigger now inserts (NEW.post_id, 1) or (OLD.post_id, -1) into post_like_deltas, and inserts never wait on each other. The fold deletes only the rows its snapshot can see, so a delta committed while it runs stays for the next pass. A thousand likes on one post become one update, and the row lock is held for one statement every few seconds instead of once per like.

This is what the gallery's busiest counters already do. The API gateway's usage_counters.request_count is "incremented by a flush job in batches, never once per request". YouTube's videos.view_count is "refreshed from the daily rollup", and TikTok's is "rolled up from watch_events". Both are view counts, which have no child row worth keeping per event. Likes and follows do have rows, so for them the delta table is an optimisation for the hot few, not the default.

Keep the counter out of indexes where you can. PostgreSQL can only do a heap-only tuple (HOT) update, which skips writing new index entries, when the update doesn't modify any indexed column. Seven gallery counters are indexed for sorting, such as YouTube's (video_id, parent_id, like_count) for top comments, and every increment on those writes to the index as well as the table. If you need the sort, it is a fair price. Otherwise, sort the top N in memory.

How do you find and repair a drifted counter?

Compare the stored number with a real count, and fix the rows that disagree:

PostgreSQL
SELECT p.id, p.like_count, coalesce(l.n, 0) AS actual
FROM posts p
LEFT JOIN (
  SELECT post_id, count(*) AS n FROM post_likes GROUP BY post_id
) l ON l.post_id = p.id
WHERE p.like_count <> coalesce(l.n, 0);

UPDATE posts p
SET like_count = (SELECT count(*) FROM post_likes l WHERE l.post_id = p.id)
WHERE p.id BETWEEN 1 AND 10000
  AND p.like_count <> (SELECT count(*) FROM post_likes l WHERE l.post_id = p.id);

Run the repair in primary-key ranges so each batch holds its locks for a moment, and log how many rows each run fixed. That number is the useful output: zero every night means the trigger covers every write path, and a steady trickle means something writes around it. The GitHub schema's note on issues.comment_count builds this in ("recomputed rather than trusted during repair jobs"). The MySQL form uses a multi-table update:

MySQL
UPDATE posts p
LEFT JOIN (
  SELECT post_id, COUNT(*) AS n FROM post_likes GROUP BY post_id
) l ON l.post_id = p.id
SET p.like_count = COALESCE(l.n, 0)
WHERE p.like_count <> COALESCE(l.n, 0);

When we ran it on MySQL 8.4 after the unpatched cascade from the previous section, it set both posts back to zero.

Should a count column be integer or bigint?

integer stops at 2,147,483,647. That is plenty for likes on a post or members of a group, and short for anything that sums views. In the gallery, 81 of the 96 cached counters are integer, 8 are smallint, and the 7 bigint ones are all views or uses: video views on YouTube and TikTok, link clicks, a sound used across TikTok. TikTok's users.total_like_count, lifetime likes across every video, is bigint with the reason in the note: "a single creator can pass two billion". Widening an integer column later rewrites the table in PostgreSQL, so choose before the table is large.

How do you add a counter in drawDB?

Open the Instagram schema or the TikTok schema in the editor, add the _count column to the parent table with a default of 0, and put like_count >= 0 in the column's Check expression field, which every drawDB exporter writes out inline. drawDB doesn't model triggers, so the trigger, the delta table's fold and the repair job go in your migration. The counter column, the child table and its cascade all export with the schema. If the count you are adding is a balance of money rather than a tally of rows, read account balance vs ledger first. A balance needs its history, and a like count doesn't.

Frequently asked questions

Should the like count be exact?

The stored number should converge to the exact count, but nobody notices if a viral post shows 10,482 likes for a few seconds after the 10,483rd. That is why the hot-row fix is a delta table folded every few seconds: it trades a short lag for no lock queue. Counts that gate an action, such as invite uses against max_uses or clicks against a link's cap, are different: increment them in the same statement that checks the limit.

Can I use a materialized view instead of a count column?

For a leaderboard or a nightly report, yes. For a number on every feed card, no: PostgreSQL's REFRESH MATERIALIZED VIEW recomputes the whole view, so it is either stale or expensive, and the view is a second table you join on every read. A column on the parent row is read for free with the row you are already loading.

How do I add a count column to a table that already has millions of rows?

Add the column with DEFAULT 0, create the trigger, then backfill in primary-key batches with the repair UPDATE from this post. Create the trigger first. A like that lands mid-backfill is then either counted by the trigger after its batch ran, or picked up by the recount before it. Run the drift check once afterwards to catch the few that raced a batch.

Does a counter trigger slow down inserts?

Each like becomes two writes, the like row and one row update on the post, plus the row lock on the post until commit. That is cheap until thousands of transactions want the same post row in the same second. Measure the lock waits on your most popular rows before reaching for a delta table; most counters never get there.