- Home
- Skills
- Code Quality & Review
- Catch Mongoose write races before they double-charge
Works with the AI Agents you already use
Catch Mongoose write races before they double-charge
Production runs many at once, payment providers retry webhooks until they get a 2xx, and queues deliver at least once.
$6
Catch Mongoose write races before they double-charge
Example session with this skill installed
Review services.ts and models.ts for race conditions: user registration, checkout (stock + wallet + order), the payment-provider webhook (retried until it gets a 2xx) and adding items to a pending order.
- Read your context and instructions
- Compiled the catch mongoose write
Write race review: services.ts + models.ts
Verdict: 2 Critical, 3 High — the payment webhook can credit a wallet many times, and two sign-ups can create duplicate accounts.
Assumed Mongoose 9.x (no package.json provided).
Write paths
| Entry point | Writes | Trigger | Concurrent / repeated? |
|---|---|---|---|
| register | users | sign-up form | concurrent |
| checkout | products, users, orders (+ email) | user click | concurrent |
| onPaymentSucceeded | users or orders (+ email) | webhook, retried until 2xx | repeated by design |
| addItem | orders | user click | concurrent, and with the webhook |
Findings (most severe first)
[Critical] R7 Payment webhook credits the wallet again on every redelivery
Evidence: if (!order) { await User.updateOne({ _id: event.userId }, { $inc: { walletBalance: event.amount } }); return; } — nothing records that the event was processed.
Interleaving
Delivery 1: no order → $inc +50 → 2xx lost on the provider side
Delivery 2: no order → $inc +50 again → 100 credited for one 50 payment
Fix: insert a ProcessedEvent with a unique index on paymentIntentId and apply the $inc in the same transaction; treat error 11000 as "already processed".
Confidence: confirmed from code
[Critical] R1 Duplicate accounts: email uniqueness checked only in code
Evidence: findOne({ email }) then User.create(...); userSchema.index({ email: 1 }) is non-unique.
Interleaving: A and B both find nothing, both create.
Fix: { unique: true } on the index (check for existing duplicates first), map 11000 to "Email already registered".
Confidence: confirmed from code (unless a unique index exists outside these files)
[High] R8 Order numbers read outside the transaction can repeat
Evidence: Order.findOne().sort({ number: -1 }) without the session, then + 1; no unique index on number.
Fix: counter document with $inc and returnDocument: 'after', plus a unique index.
[High] R6 Confirmation email sent inside the transaction callback
Evidence: await mailer.send(...) inside connection.transaction(...). The helper retries the callback on transient errors → duplicate emails, or an email for an order that never committed.
Fix: send after the transaction resolves.
[High] R3 Items can be added to an order that was already paid
Evidence: addItem checks status !== 'pending' on a read, then saves; the webhook's status $set doesn't bump __v, so the array version check doesn't catch it. The webhook also turns a cancelled order into paid.
Fix: Order.updateOne({ _id, status: 'pending' }, { $push: { items: item } }) and check modifiedCount; guard the webhook transition the same way.
[Medium] R4 Two concurrent addItem calls: one fails with an unhandled VersionError (no silent loss)
Looked risky, but safe
- Stock and wallet read-modify-write inside checkout: reads and saves both use the transaction session, so concurrent checkouts conflict and are retried.
Questions
- Is every environment a replica set? Transactions don't work on a standalone server.
- Is a unique index on users.email created elsewhere?
Connects securely to your tools. The creator never sees your data.
About this skill
Why
findOne → decide in JavaScript → save() is correct when one request runs at a time. Production runs many at once, payment providers retry webhooks until they get a 2xx, and queues deliver at least once. The result: two accounts with the same email, a wallet credited twice, an item added to an order that was already paid. Tests that call the function once never see it.
What it checks
For every write path (route, service, job, queue consumer, webhook) it asks: what if this runs twice at the same time, or twice in a row? Nine patterns:
- R1 check-then-insert or upsert without a unique index
- R2 read-modify-write of the same field (balances, stock, counters)
- R3 status transitions without the expected status in the filter
- R4 whole-array overwrites racing with query updates that skip versioning
- R5 multi-document invariants without a transaction (and when you don't need one)
- R6 transactions that aren't: operations missing
{ session }, side effects inside the retried callback - R7 webhook / queue handlers that aren't idempotent
- R8 "next number" generated with
max + 1 - R9
updateMany/bulkWriteretried as if all-or-nothing
What you get
A write-path table (trigger, can it run concurrently or repeatedly), then findings ranked Critical → Low, each with evidence (including the relevant index lines or their absence), a Request A / Request B interleaving, a fix sketch using your own model names, and a confidence label. A short "looked risky, but safe" list shows what was examined and cleared — for example a read-modify-write that is already protected by a transaction.
Limits
Reads files only (optionally read-only git diff/log/show). Never connects to a database. Mongoose/MongoDB details (save() behaviour, default versioning, transaction helpers, returnDocument) were checked against Mongoose 9.x docs and source and the MongoDB manual in November 2026.
Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for Code Quality & Review.
Code review only: never runs the code, connects to MongoDB or load-tests, so timing bugs are shown as interleavings, not reproduced. Cannot see indexes defined outside the provided files. Does not review query performance, schema design, validation, authentication or general security (serious unrelated issues get a one-line pointer). Focused on Mongoose / MongoDB Node.js driver; not for SQL ORMs.
How to use
- 1
Connect your agent to the Agensi MCP
Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup
- 2
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before buying a skill.
Reviews
No reviews yet
Be one of the first to try it. Every listed skill goes through the trust checks below.
Security scanned
Checked by our 8-point scan before listing
Fresh listing
Recently published to Agensi
Money-back guarantee
Doesn't do what its page promises? You get your money back.
Trust & safety
Security scan
Security scan passed 4 days ago
- Software
Git
Permissions
File Scopes
read/grep/glob: to open the models (schemas and indexes) and every file a write path touches. bash is optional and limited to read-only git commands (git diff, git log, git show) to focus on changed code. The skill never writes files, installs packages, connects to a database or contacts any network host.