Skip to content
This repository was archived by the owner on Nov 5, 2025. It is now read-only.
This repository was archived by the owner on Nov 5, 2025. It is now read-only.

Handle potential race conditions when creating models in DB #77

@jtourkos

Description

@jtourkos

Description:

Right now we call:

const accountSeenEvent = await AccountSeenEventModel.create(
  {
    accountId,
    repoAccountId,
    receiverAccountId,
    refundAccountId,
    deadline,
    logIndex,
    blockNumber,
    blockTimestamp,
    transactionHash,
  },
  { transaction },
);

This is fine because we only run one instance of the service today.
However, if we scale horizontally (multiple workers/processes), two inserts of the same (transactionHash, logIndex) could happen concurrently. Since that pair is our composite primary key, the second insert would throw a SequelizeUniqueConstraintError.

Note:
This is just one example (AccountSeenEvent). We currently have similar Model.create(...) logic in multiple places across the codebase. The same race condition could appear anywhere we rely on PKs/unique keys to enforce idempotency.

Impact:

  • No data corruption (the PK/unique constraints prevent duplicates).
  • But in multi-instance setups we’ll see noisy errors unless we handle them gracefully.

Proposed solution:
Introduce an idempotent wrapper (e.g. ensureModelCreated(...)), that:

  • Tries create.
  • If a PK/unique conflict occurs, fetches and returns the existing row.
  • Otherwise rethrows.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels
    No fields configured for Improvement.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions