
SaaS Unique Constraints: Define Business Identity Before Preventing Duplicate Records
Define tenant-scoped business identity, normalization, null handling, and conflict recovery before adding database uniqueness rules.
MVPs & SaaS Projects
Understand sequence gaps, concurrent allocation, and import recovery while keeping row identifiers separate from business numbering rules.

LET’S BUILD SOMETHING USEFUL
Talk to ATARAXY DEVELOPERS (SMC-PRIVATE) LIMITED about your website, app, or custom software.
A SaaS team notices that a table contains records 1041 and 1043 but no 1042. Someone assumes a customer record was lost and proposes resetting the sequence to fill the gap. That response can turn a normal allocation outcome into an actual identity problem. A database sequence allocates numbers; it is not a complete history of committed business records.
Before changing a sequence, establish what the number is supposed to mean. A technical row identifier, an externally displayed reference, and a formally issued business number may have different requirements. Consider a service platform where draft requests are frequently cancelled or retried. Its internal request ID should remain stable and unique, while a separate customer-facing document number may be assigned only after a defined approval step. Combining those meanings makes routine failures unnecessarily difficult to explain.
PostgreSQL documents nextval as an atomic operation: concurrent callers receive distinct values from the sequence. It also explains that values obtained by a transaction are not reclaimed when that transaction aborts. Aborts, crashes, and conflict-handling inserts can therefore leave gaps. The sequence manipulation reference explicitly warns against treating sequence objects as a mechanism for gapless numbering.
For application design, interpret the allocated value as an identity candidate that becomes part of a durable record when the surrounding transaction commits. Keep a primary key or other appropriate uniqueness constraint on the table. Sequence configuration, manual inserts, or administrative resets should not be allowed to undermine the table’s integrity. Do not replace the allocator with a read of the current maximum plus one; concurrent writers can observe the same maximum and propose the same next value unless a separate coordination mechanism is introduced.
Start with the question that matters: is an expected business operation missing? Check the request’s operation ID, application logs, transaction result, and any external confirmation. A gap in a numeric range alone cannot answer that question. The platform may have attempted an insert, encountered a validation or uniqueness conflict, and correctly left no committed row. Counting missing integers would then report an incident that never occurred.
Conversely, a continuous range does not prove every customer operation was processed correctly. A request can fail before any number is allocated, or a record can contain the wrong data despite having a perfectly ordinary ID. Build reconciliation around business events and durable outcomes. If a customer received a confirmation, locate the committed record associated with that confirmation. If the outcome is unknown after a network failure, use the application’s duplicate-safe operation lookup rather than guessing from the sequence’s current value.
Allocation order is not a reliable substitute for commit order. Two transactions can obtain numbers and finish in a different sequence because one waits on another resource. A list ordered by ID may be convenient, but its meaning should be explicit. If users need to see when a request was submitted, store and display the appropriate event time. If a workflow needs an ordered event stream, design that ordering rather than inferring it from an unrelated row identifier.
Likewise, the largest ID is not the number of records. Gaps, deleted rows, imports, and configuration changes all break that shortcut. Use an actual count or a defined reporting aggregate for the question being asked. For pagination, combine a stable ordering contract with the cursor semantics the API promises. Avoid letting a dashboard label such as “Total requests” come from a maximum identifier simply because the query is cheap. The number may look plausible while being consistently wrong.
If a customer-facing document needs a controlled numbering policy, define that policy with the business owner. Decide when a number is issued, what happens when a document is cancelled, whether numbering is scoped by organization or period, and how corrections are represented. Do not promise that an ordinary database sequence satisfies a specialized accounting or regulatory requirement. The relevant business rules need their own review and implementation.
A possible design assigns an immutable internal ID at record creation and a separate issued reference during a controlled finalization transaction. A coordinated counter row can serialize issuance within a defined scope, but it brings contention, failure handling, and operational decisions of its own. Preserve cancelled or voided issued references according to the approved policy rather than reusing them casually. Test concurrent finalization and rollback behavior. The key is to make the business number’s lifecycle explicit, not to disguise a technical allocator as a business ledger.
Imports that insert explicit IDs can leave the associated sequence behind the data, depending on how the import is performed. Review the relationship during a controlled migration. Stop or coordinate competing writers before calculating and applying a correction, then test a normal insert afterward. A repair based on a stale maximum can collide with activity that occurred while the calculation was being made. Keep a backup and a concrete rollback plan for the migration itself.
PostgreSQL documents that setval changes are immediately visible to other transactions and are not undone by a transaction rollback. Its optional boolean argument also changes what the next allocation returns. Read the exact behavior before using it in a maintenance script, and include empty-table and nondefault-increment cases in the review. Never reset a sequence simply to make the visible numbers look tidy. Administrative privileges to alter sequence state should be limited to the workflows and people who actually need them.
A numeric identifier should not serve as an authorization check. An API must verify that the authenticated user may access the requested record, regardless of whether the ID is sequential or difficult to guess. If exposing volume or internal structure is undesirable, use a separate public reference chosen for that purpose. Still retain the same server-side access control. Changing the shape of an identifier does not fix an endpoint that returns another tenant’s data.
Document the expected presence of gaps in operational guidance so support staff can explain them accurately. AI-assisted incident summaries should draw from confirmed transaction evidence, not label every missing number as a deleted customer request. Add tests for aborted inserts, conflict handling, concurrent requests, and imported IDs. Monitor duplicate-key failures and unresolved business operations separately from sequence gaps. This gives the team signals tied to actual integrity and workflow problems instead of encouraging cosmetic repairs to normal allocator behavior.
PostgreSQL sequences are useful identity allocators when their limits are understood. Accept gaps, keep table constraints in place, and investigate missing business outcomes through durable operation evidence. Use explicit timestamps and counts for reporting, and design separate issuance rules when a business reference has stronger requirements. Treat sequence maintenance as coordinated administrative work. These distinctions let an MVP grow without turning ordinary retries and rollbacks into confusing numbering incidents or risky attempts to reuse identities that were never meant to carry that meaning.
LET’S BUILD SOMETHING USEFUL
Talk to ATARAXY DEVELOPERS (SMC-PRIVATE) LIMITED about your website, app, or custom software.