QA
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→

More REST APIs & Web Services Interview Questions

Beginner LevelREST APIs & Web Services

What is HTTP Method Idempotency and how do you implement Idempotency Keys for REST APIs?

Beginner LevelREST APIs & Web Services

What are standard HTTP Status Codes (200, 201, 204, 400, 401, 403, 404, 409, 429, 500, 503)?

Beginner LevelREST APIs & Web Services

What are HTTP Verbs (GET, POST, PUT, PATCH, DELETE) and when to use PUT vs PATCH?