Reaction controls look simple, but users can click twice, clients can retry, and several devices can update the same article concurrently. The database should enforce the rule that one actor has at most one active reaction of a given kind on a content item.
Put uniqueness in the database
Create a unique constraint over the actor, content ID, and reaction type—or over actor and content if the product allows only one reaction total. The API can then implement an idempotent set operation rather than blindly incrementing a counter. Verify that the actor is authenticated and the content is visible before changing state.
Treat aggregate counts as derived data. Counting rows on demand may be sufficient at small scale; a denormalized counter can help at higher read volume but must be updated transactionally or reconciled from the source records. Never trust a count supplied by the browser.
Handle toggles and retries
A “toggle” request can be ambiguous when repeated: the first request adds the reaction and the retry removes it. Prefer explicit
setremoveTest simultaneous requests, duplicate retries, switching reaction type, deleted content, and permission changes. Keep analytics events separate from the transactional reaction state so analytics failure cannot undo the user’s action. The interface should announce the new state accessibly and work without relying on color alone.
Make retries and toggles mean different things
When a client retries a request to add a clap, the desired final state is still one clap for the same article and reader. A unique key on the pair makes that condition enforceable even when workers receive the requests concurrently. PostgreSQL provides ON CONFLICT DO NOTHING and RETURNING, letting the service see whether an insert created a row. PostgreSQL unique indexes · PostgreSQL INSERT
On a PostgreSQL 16.14 test table, the first insert for one pair returned one row, and the repeated insert returned zero rows. The stored count remained one. Emit a notification only when a real insert occurred. A toggle endpoint has a different contract because executing it twice can reverse the desired result. Use explicit add and remove semantics where clients need retries to converge on a predictable state.
Worked example
This disposable session shows exactly what RETURNING gives the service on the first insert and a retry. The final SELECT verifies the stored count.
sqlCREATE TEMP TABLE reaction ( blog_id text, user_id text, PRIMARY KEY (blog_id, user_id) ); INSERT INTO reaction VALUES ('article-a', 'reader-a') ON CONFLICT (blog_id, user_id) DO NOTHING RETURNING blog_id, user_id; INSERT INTO reaction VALUES ('article-a', 'reader-a') ON CONFLICT (blog_id, user_id) DO NOTHING RETURNING blog_id, user_id; SELECT count(*) AS reaction_total_after_retry FROM reaction;




Community
Discussion
Loading comments…