Repository navigation
Expand file tree
/
Copy pathREFLECTION.essay
More file actions
13 lines (9 loc) · 2.58 KB
/
Copy pathREFLECTION.essay
File metadata and controls
13 lines (9 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
Q1
Why must uniqueness be enforced by the database under concurrency?
Application-level check-then-insert (`find_one` followed by `insert_one`) suffers from a TOCTOU race condition: two concurrent requests—especially across separate service instances—can both observe no existing record for `(owner, sku)` and both proceed to insert, creating duplicate items. Enforcing a compound unique index on `(owner, sku)` inside MongoDB makes uniqueness validation and document insertion atomic at the storage layer, guaranteeing that at most one concurrent insert succeeds while any competing insert fails with error code 11000 (`DuplicateKeyError`), which the service safely maps to `409 sku_conflict`.
Q2
Explain the difference between constructing an item dictionary, inserting it and updating a stored MongoDB document.
Constructing an item dictionary only allocates an in-memory Python `dict` inside the current process; it is lost when the request ends, bypasses database `$jsonSchema` and unique-index checks, and is invisible to other requests. Inserting it with `insert_one` persists a new document to MongoDB, enforces schema and uniqueness rules, and allows subsequent queries to read back what was actually stored. Updating a stored document with `find_one_and_update` (filtering by `_id`, `owner`, and `version`, applying `$set` and `$inc`, and passing `ReturnDocument.AFTER`) atomically verifies ownership and optimistic lock version, persists the field changes and version increment in one database operation, and returns the post-update persisted state rather than stale pre-update data.
Q3
How would retry-safe inventory adjustments differ from setting an absolute quantity?
Setting an absolute quantity with optimistic locking (`version` check + `$inc`) prevents stale overwrites on retries because once the first request succeeds and increments `version`, a retried request with the old `version` gets `409 version_conflict`; however, it requires reading the current state first and serializes concurrent adjustments. Relative adjustments (applying a delta such as `-5` or `+10`) allow concurrent non-conflicting stock changes, but a naive `$inc` is not idempotent: if a client retries after a network timeout when the first write already succeeded, the delta would be applied twice. Making relative adjustments retry-safe requires an idempotency key (or unique adjustment/transaction ID) stored atomically with the stock update—along with range guards such as `quantity + delta` within `[0, 1000000]`—so that any retry sees the already-recorded key and returns the original outcome instead of re-applying the delta.