Skip to content

fix(queue): enforce idempotent consumption with unique keys#1

Open
tobechi-dev wants to merge 3 commits into
mainfrom
fix/queue-idempotency-fresh
Open

fix(queue): enforce idempotent consumption with unique keys#1
tobechi-dev wants to merge 3 commits into
mainfrom
fix/queue-idempotency-fresh

Conversation

@tobechi-dev

Copy link
Copy Markdown
Owner

Summary

Implements idempotent consumer to prevent duplicate side effects when messages are redelivered or processed concurrently under at-least-once delivery.

Changes

New Files

  • src/services/idempotentConsumer.ts - Core IdempotentConsumer class
  • src/__tests__/idempotentConsumer.test.ts - Unit tests
  • tests/integration/idempotentConsumer.test.ts - Integration tests
  • docs/idempotent-consumer.md - Technical documentation

Bug Fix

  • src/db/repositories/idempotencyRepository.ts - Fixed JSON parse for responseBody

Implementation Details

The idempotent consumer uses write-layer deduplication:

  1. Check: Look up message key in idempotency_keys table before processing
  2. Skip: If key exists, return cached result (already processed)
  3. Process: If not exists, run handler and store result with UPSERT
  4. TTL: Results expire automatically (default 24 hours)

This ensures messages are processed exactly once even when:

  • Consumer crashes and message is redelivered
  • Network timeouts cause broker retries
  • Multiple workers process concurrently

Testing

All tests pass:

  • ✅ 10 unit tests
  • ✅ Integration tests (require real PostgreSQL)

Related Issue

Fixes CredenceOrg#231 - [Fresh 2026-04][Backend] Queues: idempotent consumer under at-least-once delivery (dedupe at write layer)

- Add IdempotentConsumer class for at-least-once message delivery
- Use idempotency_keys table with unique constraints and upserts
- Check cache before processing, store result after completion
- Skip reprocessing for duplicate messageIds within TTL window
- Add unit tests for core idempotent processing flows
- Add integration tests for duplicate message handling

Branch: fix/queue-idempotency-fresh
- Document problem: at-least-once delivery causing duplicates
- Solution architecture: write-layer deduplication with unique keys
- Implementation details: flow diagrams, class methods, configuration
- Why chosen approach over alternatives (locks, client-side)
- Files created (service, tests) and edited (bug fix)
- Usage examples for queues, webhooks, scheduled jobs
- Performance considerations and future enhancements
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Fresh 2026-04][Backend] Queues: idempotent consumer under at-least-once delivery (dedupe at write layer)

1 participant