Intermediate LevelREST APIs & Web Services
How do you implement Optimistic Concurrency Control using ETag middleware in Express?
❓ Interview Prompt: Explain optimistic locking middleware, computing response hashing, comparing `If-Match` headers, and throwing `412 Precondition Failed`.
Implementing ETag concurrency middleware in Express to protect database records from race conditions:
Middleware Flow:
1
On 'GET': Generate MD5 hash of entity record and return in 'ETag' header.
2
On 'PUT'/'PATCH': Extract 'If-Match' header from request. Fetch current database record ETag hash.
3
If 'If-Match' header != current DB hash $\rightarrow$ Abort operation and return '412 Precondition Failed'!
Code Implementation Example
typescript
export async function requireMatchingETag(req: Request, res: Response, next: NextFunction) {
const ifMatch = req.header('If-Match');
if (!ifMatch) return res.status(428).json({ error: 'Precondition Required: Missing If-Match header' });
const currentRecord = await db.item.findUnique({ where: { id: req.params.id } });
const currentETag = '"${computeHash(currentRecord)}"';
if (ifMatch !== currentETag) {
return res.status(412).json({ error: 'Precondition Failed: Resource has been modified by another process' });
}
next();
}💡Express middleware enforcing ETag If-Match optimistic concurrency validation.
🎯 Interview Key Takeaway
Enforce 428 Precondition Required and 412 Precondition Failed using ETag middleware to protect database updates from race conditions.
#ETag#Optimistic Locking#Express#Intermediate
Back to all REST APIs & Web Services Questions→