跪拜 Guibai
← All articles
Backend

Stop duplicate form submissions: front-end guards, idempotency keys, and database constraints

By 时间海871 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Duplicate submissions corrupt signup lists and confuse users, but the fix is well understood: combine front-end interception with idempotency at the API and uniqueness at the database layer. Western developers building any registration flow can apply these concrete patterns now, saving themselves from the classic race-condition bugs that surface under real network latency.

Summary

Duplicate form submissions happen in the gap between clicking submit and receiving the response. On a slow network, users click again or refresh, and the server may have already written the record. The fix starts on the front end: route every submission path (button, Enter key, programmatic) through the form's submit event, cancel the default action, and set an in-flight flag before any async call so a second trigger can't slip through. Disable the button and show a status message, and use form.requestSubmit() to keep native validation.

Backend reliability needs more than a flag. The API should support an idempotency key: a random ID generated per submission, reused on retries after timeout. The server binds the key to the user and operation, stores a digest of key fields, and returns the original result for the same key and content, or a conflict if the content changed. For concurrent requests, a simple check-then-insert race can let duplicates through; a unique constraint on (user, operation, key) plus a transaction ensures only one write wins. When an event limits one registration per account, add a separate unique constraint on (event, account), so multiple tabs with different keys still collapse to one record.

Joint debugging should deliberately simulate slow and failing responses: delay the API, spam the button, drop the first response, retry with the same key, and submit from two tabs. Verify both the browser feedback and the actual rows in the database match. The article's author (时间海871) describes comparing visible UI states with server-side records to confirm the user always knows what state their submission reached.

Takeaways
— Route all submission triggers (click, Enter, programmatic) through the form's submit event and cancel the default action to keep a single control point.
— Set an in-flight submission flag before the first async operation, not after, so two rapid triggers can't both pass the check.
— Use form.requestSubmit() for programmatic submissions; form.submit() skips validation and the submit event.
— Capture form data before disabling input fields, since browsers exclude disabled fields from serialized form data.
— For retries, generate a random idempotency key per logical operation and reuse it with the same request body on timeout; only use a new key after a field-validation correction.
— The server must bind idempotency keys to the current user and API operation, store a digest of key request fields, and retain the result (like the registration ID) for replay, with a defined retention window.
— When the database is shared between registration and idempotency records, wrap key occupation, record creation, and result storage in a single transaction; the loser reads the committed result on unique-key conflict.
— Add a unique constraint on (event ID, account ID) to enforce one registration per account, preventing duplicate submissions even from different tabs with different idempotency keys.
— Debug by deliberately delaying the API, dropping the first response, retrying, and submitting from two tabs; check both UI feedback and the actual row count in the database.
— For long-running operations, return a processing status and let the page poll, rather than holding a connection open.
Conclusions

Idempotency keys handle replayed requests but not concurrent requests that reach the server before the first write commits; only a database-level unique constraint can truly resolve that race.

The advice to capture form data before disabling inputs is a subtle reminder that browser form serialization drops disabled fields, which can silently break a submission if done in the wrong order.

Requiring the same key with different content to return a conflict, rather than just overwriting, gives clients a safe way to distinguish genuine retries from user edits that should create a new operation.

The multi-tab scenario shows that front-end flags and idempotency keys are insufficient for true uniqueness; the final authority must be a database constraint that spans the whole account, not just a single request.

Concepts & terms
idempotency key
A unique client-generated identifier attached to a request so the server can recognize replays of the same logical operation and return the original result instead of creating a duplicate.
unique constraint
A database rule that prevents two rows from having the same values in specified columns, used here to enforce that only one registration can exist per user, per event.
requestSubmit()
A method on HTMLFormElement that triggers form validation and fires the submit event, unlike submit() which bypasses validation and event handlers.
From the discussion

The discussion centers on the necessity of reusing the original idempotency key and request payload when retrying after timeouts, and on the three-layer defense strategy as the trustworthy solution. A shared conviction emerges that button disabling alone is insufficient under concurrency; idempotency keys combined with unique constraints are required, and reusing the same key for retries is a critical nuance.

— Retries after a timeout must reuse the original idempotency key and request body to preserve idempotent semantics.
— Button disabling is an inadequate guard against duplicate submissions; the three-layer approach (front-end guard, idempotency key, unique constraint) is the reliable path.
— Reusing the same key across retries is a critical implementation detail that prevents accidental duplicate records.
Featured comments
卷土的土

Retrying with the same key and same content after a timeout is the most critical part.

组合搭配函数

This three-layer duplicate-prevention approach is solid. Relying only on graying out the button really can't hold up; once concurrency hits, you have to depend on idempotency keys plus unique constraints. Reusing the same key for retries is a thoughtful detail.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗