πŸ—οΈ Architecture

Inbox Pattern

Inbox Pattern Β· Idempotent Consumer Pattern

The Inbox Pattern is an idempotency pattern that prevents duplicate message processing in message-based distributed systems. It stores the unique ID of each received message in a separate table (Inbox), so that even if the same message arrives again, it is not processed twice.

πŸ“– Detailed Explanation

Why Is the Inbox Pattern Needed?

In distributed messaging systems, At-Least-Once delivery guarantees prevent message loss, but during network failures or Consumer restarts, the same message may be delivered multiple times. As a result:

  • Duplicate order creation: the same order is processed twice
  • Duplicate payment deduction: a single payment request is charged double the amount
  • Excessive inventory deduction: the same inventory decrease is executed multiple times
  • Duplicate notification delivery: the same notification is sent to the user multiple times

How the Inbox Pattern Works

The Inbox Pattern determines whether a message is a duplicate by recording the received message's unique identifier (Message ID) in a persistent store (Inbox table):

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Inbox Pattern Flow β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ β”‚ β”‚ Message Queue Consumer Service Database β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ Msg A │────Consume─────▢│ 1. Extract β”‚ β”‚ INBOX β”‚ β”‚ β”‚ β”‚ (ID:123)β”‚ β”‚ Msg ID β”‚ β”‚ TABLE β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ Msg A β”‚ β”‚ 2. Check │──EXISTS?────▢│ β”Œβ”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β”‚ (ID:123)β”‚ β”‚ Inbox β”‚ β”‚ β”‚ID:123β”‚ β”‚ β”‚ β”‚ β”‚ (retry) β”‚ β”‚ │◀─YES/NO──────│ β”‚ID:456β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ID:789β”‚ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ 3. If NEW: β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ - Insert │──INSERT─────▢│ β”‚ β”‚ β”‚ β”‚ - Process β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ BUSINESS β”‚ β”‚ β”‚ β”‚ 4. If DUP: β”‚ β”‚ TABLE β”‚ β”‚ β”‚ β”‚ - Skip β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β”‚ - ACK β”‚ β”‚ β”‚Ordersβ”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚Items β”‚ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ 핡심: Message IDλ₯Ό Inbox ν…Œμ΄λΈ”μ— μ €μž₯ν•˜μ—¬ 쀑볡 체크 β”‚ β”‚ μ „λž΅: INSERT와 λΉ„μ¦ˆλ‹ˆμŠ€ λ‘œμ§μ„ ν•˜λ‚˜μ˜ νŠΈλžœμž­μ…˜μœΌλ‘œ 묢음 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Processing Steps

  1. Receive message: the Consumer receives a message from the Message Queue
  2. Extract ID: extract the unique identifier (Message ID, Idempotency Key) from the message
  3. Duplicate check: check whether that ID exists in the Inbox table
  4. Conditional processing:
    • New message: insert the ID into the Inbox + execute business logic (in the same transaction)
    • Duplicate message: skip the business logic and send only the ACK
  5. Send ACK: notify the Message Queue that processing is complete
πŸ’‘ Core Principle The Inbox INSERT and the business logic must be executed in the same transaction. This prevents the inconsistent state in which "the message was recorded in the Inbox but the business logic failed."

Inbox Table Design

The Inbox table can be designed with a simple structure:

-- κΈ°λ³Έ Inbox ν…Œμ΄λΈ”
CREATE TABLE inbox (
    message_id    VARCHAR(255) PRIMARY KEY,  -- λ©”μ‹œμ§€ 고유 ID (UUID, Correlation ID λ“±)
    message_type  VARCHAR(100) NOT NULL,      -- λ©”μ‹œμ§€ νƒ€μž… (OrderCreated, PaymentCompleted λ“±)
    received_at   TIMESTAMP DEFAULT NOW(),    -- μˆ˜μ‹  μ‹œκ°
    processed_at  TIMESTAMP,                  -- 처리 μ™„λ£Œ μ‹œκ° (nullable)
    payload       JSONB                       -- 원본 λ©”μ‹œμ§€ μ €μž₯ (디버깅/재처리용, optional)
);

-- 쑰회 μ„±λŠ₯을 μœ„ν•œ 인덱슀
CREATE INDEX idx_inbox_received_at ON inbox(received_at);
CREATE INDEX idx_inbox_message_type ON inbox(message_type);

-- 였래된 λ ˆμ½”λ“œ 정리λ₯Ό μœ„ν•œ νŒŒν‹°μ…”λ‹ (선택사항)
-- λ©”μ‹œμ§€ 보관 기간에 따라 일별/주별 νŒŒν‹°μ…˜ ꡬ성

Inbox Pattern vs Outbox Pattern

Inbox and Outbox are complementary patterns that ensure reliability at both ends of message processing:

Category Inbox Pattern Outbox Pattern
Location Consumer (receiving side) Producer (sending side)
Purpose Prevent duplicate message processing Prevent message loss
Operation Check for duplicates by message ID, then process Store the business logic and the message in a single transaction
Problem Solved Duplicate processing caused by At-Least-Once Message publishing failure after a DB commit
Table Role Records IDs of processed messages Temporarily stores messages to be published
Used Together Outbox β†’ Message Queue β†’ Inbox (End-to-End reliability)

πŸ’» Code Example

TypeScript + PostgreSQL Implementation

A complete example implementing the Inbox Pattern in a Node.js environment:

// inbox/inbox.entity.ts
import { Entity, PrimaryColumn, Column, CreateDateColumn } from 'typeorm';

@Entity('inbox')
export class InboxEntity {
  @PrimaryColumn('varchar', { length: 255 })
  messageId: string;

  @Column('varchar', { length: 100 })
  messageType: string;

  @CreateDateColumn()
  receivedAt: Date;

  @Column('timestamp', { nullable: true })
  processedAt: Date | null;

  @Column('jsonb', { nullable: true })
  payload: Record<string, unknown>;
}

// inbox/inbox.repository.ts
import { Injectable } from '@nestjs/common';
import { DataSource, EntityManager } from 'typeorm';
import { InboxEntity } from './inbox.entity';

@Injectable()
export class InboxRepository {
  constructor(private dataSource: DataSource) {}

  /**
   * λ©”μ‹œμ§€κ°€ 이미 μ²˜λ¦¬λ˜μ—ˆλŠ”μ§€ 확인
   */
  async isProcessed(messageId: string): Promise<boolean> {
    const existing = await this.dataSource.manager.findOne(InboxEntity, {
      where: { messageId }
    });
    return existing !== null;
  }

  /**
   * Inbox에 λ©”μ‹œμ§€ 등둝 (νŠΈλžœμž­μ…˜ λ‚΄μ—μ„œ μ‚¬μš©)
   */
  async recordMessage(
    manager: EntityManager,
    messageId: string,
    messageType: string,
    payload?: Record<string, unknown>
  ): Promise<void> {
    const inbox = manager.create(InboxEntity, {
      messageId,
      messageType,
      payload,
      processedAt: null
    });
    await manager.save(inbox);
  }

  /**
   * 처리 μ™„λ£Œ μ‹œκ° μ—…λ°μ΄νŠΈ
   */
  async markAsProcessed(
    manager: EntityManager,
    messageId: string
  ): Promise<void> {
    await manager.update(InboxEntity, { messageId }, {
      processedAt: new Date()
    });
  }
}

// message/message-handler.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { InboxRepository } from '../inbox/inbox.repository';

interface OrderCreatedEvent {
  orderId: string;
  customerId: string;
  items: Array<{ productId: string; quantity: number; price: number }>;
  totalAmount: number;
}

@Injectable()
export class MessageHandlerService {
  private readonly logger = new Logger(MessageHandlerService.name);

  constructor(
    private dataSource: DataSource,
    private inboxRepository: InboxRepository
  ) {}

  /**
   * Inbox Pattern을 μ μš©ν•œ λ©”μ‹œμ§€ 처리
   */
  async handleOrderCreated(
    messageId: string,
    event: OrderCreatedEvent
  ): Promise<void> {
    // 1. 쀑볡 체크 (λΉ λ₯Έ μ‹€νŒ¨)
    const alreadyProcessed = await this.inboxRepository.isProcessed(messageId);
    if (alreadyProcessed) {
      this.logger.log(`Duplicate message detected: ${messageId}, skipping...`);
      return; // ACK 전솑 (λ©”μ‹œμ§€ νμ—μ„œ 제거)
    }

    // 2. νŠΈλžœμž­μ…˜μœΌλ‘œ Inbox 기둝 + λΉ„μ¦ˆλ‹ˆμŠ€ 둜직 μ‹€ν–‰
    await this.dataSource.transaction(async (manager) => {
      // 2-1. Inbox에 λ©”μ‹œμ§€ 등둝 (Race condition λ°©μ§€λ₯Ό μœ„ν•΄ νŠΈλžœμž­μ…˜ λ‚΄μ—μ„œ)
      try {
        await this.inboxRepository.recordMessage(
          manager,
          messageId,
          'OrderCreated',
          event as Record<string, unknown>
        );
      } catch (error: any) {
        // UNIQUE μ œμ•½ 쑰건 μœ„λ°˜ = λ‹€λ₯Έ μΈμŠ€ν„΄μŠ€κ°€ λ¨Όμ € μ²˜λ¦¬ν•¨
        if (error.code === '23505') { // PostgreSQL unique violation
          this.logger.log(`Concurrent duplicate: ${messageId}, skipping...`);
          return;
        }
        throw error;
      }

      // 2-2. λΉ„μ¦ˆλ‹ˆμŠ€ 둜직 μ‹€ν–‰
      await this.processOrderCreated(manager, event);

      // 2-3. 처리 μ™„λ£Œ ν‘œμ‹œ
      await this.inboxRepository.markAsProcessed(manager, messageId);
    });

    this.logger.log(`Successfully processed OrderCreated: ${messageId}`);
  }

  private async processOrderCreated(
    manager: any,
    event: OrderCreatedEvent
  ): Promise<void> {
    // μ‹€μ œ λΉ„μ¦ˆλ‹ˆμŠ€ 둜직 κ΅¬ν˜„
    // - μ£Όλ¬Έ μ—”ν‹°ν‹° 생성/μ—…λ°μ΄νŠΈ
    // - 재고 κ°μ†Œ
    // - 포인트 적립
    // - μ•Œλ¦Ό λ°œμ†‘ 이벀트 생성 (Outbox Pattern μ‚¬μš©)

    this.logger.log(`Processing order: ${event.orderId} for customer: ${event.customerId}`);

    // μ˜ˆμ‹œ: μ£Όλ¬Έ μ €μž₯
    await manager.query(
      `INSERT INTO orders (id, customer_id, total_amount, status, created_at)
       VALUES ($1, $2, $3, 'CREATED', NOW())`,
      [event.orderId, event.customerId, event.totalAmount]
    );

    // μ˜ˆμ‹œ: μ£Όλ¬Έ μ•„μ΄ν…œ μ €μž₯
    for (const item of event.items) {
      await manager.query(
        `INSERT INTO order_items (order_id, product_id, quantity, price)
         VALUES ($1, $2, $3, $4)`,
        [event.orderId, item.productId, item.quantity, item.price]
      );
    }
  }
}

// message/kafka-consumer.ts
import { Injectable, OnModuleInit } from '@nestjs/common';
import { Kafka, Consumer, EachMessagePayload } from 'kafkajs';
import { MessageHandlerService } from './message-handler.service';

@Injectable()
export class KafkaConsumer implements OnModuleInit {
  private consumer: Consumer;

  constructor(private messageHandler: MessageHandlerService) {
    const kafka = new Kafka({
      clientId: 'order-service',
      brokers: ['kafka:9092']
    });
    this.consumer = kafka.consumer({ groupId: 'order-service-group' });
  }

  async onModuleInit() {
    await this.consumer.connect();
    await this.consumer.subscribe({ topic: 'order-events', fromBeginning: false });

    await this.consumer.run({
      eachMessage: async (payload: EachMessagePayload) => {
        const { message } = payload;

        // Message ID μΆ”μΆœ (Kafkaμ—μ„œλŠ” 보톡 헀더에 포함)
        const messageId = message.headers?.['message-id']?.toString()
          ?? message.key?.toString()
          ?? `${payload.topic}-${payload.partition}-${message.offset}`;

        const event = JSON.parse(message.value?.toString() ?? '{}');

        // Inbox Pattern이 적용된 ν•Έλ“€λŸ¬ 호좜
        await this.messageHandler.handleOrderCreated(messageId, event);
      }
    });
  }
}

Java + Spring Implementation

An implementation of the Inbox Pattern using Spring Boot and JPA:

// entity/InboxMessage.java
package com.example.inbox.entity;

import jakarta.persistence.*;
import java.time.Instant;

@Entity
@Table(name = "inbox")
public class InboxMessage {

    @Id
    @Column(name = "message_id", length = 255)
    private String messageId;

    @Column(name = "message_type", length = 100, nullable = false)
    private String messageType;

    @Column(name = "received_at", nullable = false)
    private Instant receivedAt = Instant.now();

    @Column(name = "processed_at")
    private Instant processedAt;

    @Column(name = "payload", columnDefinition = "jsonb")
    private String payload;

    // Getters, setters, constructors...

    public static InboxMessage create(String messageId, String messageType, String payload) {
        InboxMessage inbox = new InboxMessage();
        inbox.messageId = messageId;
        inbox.messageType = messageType;
        inbox.payload = payload;
        return inbox;
    }

    public void markAsProcessed() {
        this.processedAt = Instant.now();
    }
}

// repository/InboxRepository.java
package com.example.inbox.repository;

import com.example.inbox.entity.InboxMessage;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface InboxRepository extends JpaRepository<InboxMessage, String> {
    boolean existsByMessageId(String messageId);
}

// service/IdempotentMessageHandler.java
package com.example.inbox.service;

import com.example.inbox.entity.InboxMessage;
import com.example.inbox.repository.InboxRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.function.Consumer;

@Service
public class IdempotentMessageHandler {

    private static final Logger log = LoggerFactory.getLogger(IdempotentMessageHandler.class);

    private final InboxRepository inboxRepository;

    public IdempotentMessageHandler(InboxRepository inboxRepository) {
        this.inboxRepository = inboxRepository;
    }

    /**
     * 멱등성이 보μž₯된 λ©”μ‹œμ§€ 처리 ν…œν”Œλ¦Ώ
     *
     * @param messageId    λ©”μ‹œμ§€ 고유 ID
     * @param messageType  λ©”μ‹œμ§€ νƒ€μž…
     * @param payload      원본 νŽ˜μ΄λ‘œλ“œ (JSON λ¬Έμžμ—΄)
     * @param handler      μ‹€μ œ λΉ„μ¦ˆλ‹ˆμŠ€ 둜직
     */
    @Transactional
    public void handleIdempotently(
            String messageId,
            String messageType,
            String payload,
            Consumer<String> handler
    ) {
        // 1. λΉ λ₯Έ 쀑볡 체크 (νŠΈλžœμž­μ…˜ μ™ΈλΆ€)
        if (inboxRepository.existsByMessageId(messageId)) {
            log.info("Duplicate message detected: {}, skipping", messageId);
            return;
        }

        // 2. Inbox 기둝 μ‹œλ„ (νŠΈλžœμž­μ…˜ λ‚΄λΆ€)
        InboxMessage inbox = InboxMessage.create(messageId, messageType, payload);

        try {
            inboxRepository.save(inbox);
        } catch (DataIntegrityViolationException e) {
            // λ™μ‹œμ„± κ²½μŸμ—μ„œ λ‹€λ₯Έ μΈμŠ€ν„΄μŠ€κ°€ λ¨Όμ € INSERT 성곡
            log.info("Concurrent duplicate detected: {}, skipping", messageId);
            return;
        }

        // 3. λΉ„μ¦ˆλ‹ˆμŠ€ 둜직 μ‹€ν–‰
        handler.accept(payload);

        // 4. 처리 μ™„λ£Œ ν‘œμ‹œ
        inbox.markAsProcessed();
        inboxRepository.save(inbox);

        log.info("Successfully processed message: {}", messageId);
    }
}

// listener/OrderEventListener.java
package com.example.order.listener;

import com.example.inbox.service.IdempotentMessageHandler;
import com.example.order.service.OrderService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

@Component
public class OrderEventListener {

    private final IdempotentMessageHandler idempotentHandler;
    private final OrderService orderService;
    private final ObjectMapper objectMapper;

    public OrderEventListener(
            IdempotentMessageHandler idempotentHandler,
            OrderService orderService,
            ObjectMapper objectMapper
    ) {
        this.idempotentHandler = idempotentHandler;
        this.orderService = orderService;
        this.objectMapper = objectMapper;
    }

    @KafkaListener(topics = "order-events", groupId = "order-service")
    public void handleOrderEvent(
            @Payload String payload,
            @Header(KafkaHeaders.RECEIVED_KEY) String messageKey,
            @Header(value = "message-id", required = false) String messageId
    ) {
        // Message ID κ²°μ • (헀더 μš°μ„ , μ—†μœΌλ©΄ Kafka key μ‚¬μš©)
        String effectiveMessageId = messageId != null ? messageId : messageKey;

        // Inbox Pattern 적용
        idempotentHandler.handleIdempotently(
            effectiveMessageId,
            "OrderCreated",
            payload,
            (p) -> {
                try {
                    OrderCreatedEvent event = objectMapper.readValue(p, OrderCreatedEvent.class);
                    orderService.processOrderCreated(event);
                } catch (Exception e) {
                    throw new RuntimeException("Failed to process order event", e);
                }
            }
        );
    }
}

Go Implementation (Concise Version)

An implementation of the Inbox Pattern in the Go language:

// inbox/handler.go
package inbox

import (
    "context"
    "database/sql"
    "encoding/json"
    "errors"
    "log"
    "time"

    "github.com/lib/pq"
)

type InboxHandler struct {
    db *sql.DB
}

func NewInboxHandler(db *sql.DB) *InboxHandler {
    return &InboxHandler{db: db}
}

// HandleIdempotently wraps message processing with inbox pattern
func (h *InboxHandler) HandleIdempotently(
    ctx context.Context,
    messageID string,
    messageType string,
    payload json.RawMessage,
    handler func(ctx context.Context, tx *sql.Tx) error,
) error {
    // 1. Quick duplicate check
    exists, err := h.checkExists(ctx, messageID)
    if err != nil {
        return err
    }
    if exists {
        log.Printf("Duplicate message: %s, skipping", messageID)
        return nil
    }

    // 2. Start transaction
    tx, err := h.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
    if err != nil {
        return err
    }
    defer tx.Rollback()

    // 3. Try to insert into inbox (handles race condition)
    err = h.insertInbox(ctx, tx, messageID, messageType, payload)
    if err != nil {
        var pqErr *pq.Error
        if errors.As(err, &pqErr) && pqErr.Code == "23505" {
            log.Printf("Concurrent duplicate: %s, skipping", messageID)
            return nil
        }
        return err
    }

    // 4. Execute business logic
    if err := handler(ctx, tx); err != nil {
        return err
    }

    // 5. Mark as processed and commit
    if err := h.markProcessed(ctx, tx, messageID); err != nil {
        return err
    }

    return tx.Commit()
}

func (h *InboxHandler) checkExists(ctx context.Context, messageID string) (bool, error) {
    var exists bool
    err := h.db.QueryRowContext(ctx,
        "SELECT EXISTS(SELECT 1 FROM inbox WHERE message_id = $1)",
        messageID,
    ).Scan(&exists)
    return exists, err
}

func (h *InboxHandler) insertInbox(
    ctx context.Context,
    tx *sql.Tx,
    messageID, messageType string,
    payload json.RawMessage,
) error {
    _, err := tx.ExecContext(ctx,
        `INSERT INTO inbox (message_id, message_type, payload, received_at)
         VALUES ($1, $2, $3, $4)`,
        messageID, messageType, payload, time.Now(),
    )
    return err
}

func (h *InboxHandler) markProcessed(ctx context.Context, tx *sql.Tx, messageID string) error {
    _, err := tx.ExecContext(ctx,
        "UPDATE inbox SET processed_at = $1 WHERE message_id = $2",
        time.Now(), messageID,
    )
    return err
}
πŸ’‘ Message ID Generation Strategies Use one of the following as the message ID:
  • UUID v4: generated by the Producer, globally unique
  • Idempotency Key: a unique key per request generated by the client
  • Business Key: a key with business meaning, such as an order ID + version combination
  • Kafka Offset: a topic-partition-offset combination (Kafka only)

βš–οΈ Comparison of Idempotency Implementation Strategies

Besides the Inbox Pattern, there are various other strategies for preventing duplicate processing:

Strategy Method Advantages Cons
Inbox Pattern Store the Message ID in a separate table General-purpose, applicable to all message types Requires additional storage space and table management
Upsert INSERT ON CONFLICT UPDATE Simple, no separate table needed Applies only to specific entities, deletion operations are difficult
Version Check Check state using the entity version Combines naturally with Optimistic Lock Requires version management logic, increased complexity
Natural Idempotency The operation itself is idempotent (e.g., SET operations) No additional implementation needed Cannot be applied to all operations (e.g., increment/decrement operations)
Deduplication Service Cache IDs in Redis/Memcached Very fast checks, easy in distributed environments Duplicates possible after TTL expiry, external dependency

When Should Which Strategy Be Chosen?

🎯 Selection Guide
  • Inbox Pattern: general-purpose message processing, diverse event types, or when audit logs are needed
  • Upsert: simple entity creation/update, when quick implementation is needed
  • Version Check: aggregates that already use versioning, DDD environments
  • Redis caching: when ultra-fast processing is needed and preventing only temporary duplicates is sufficient

πŸ› οΈ Practical Application Guide

Inbox Table Management

Over time, the Inbox table keeps growing. A cleanup strategy is needed:

-- 1. μ‹œκ°„ 기반 정리 (30일 이상 였래된 λ ˆμ½”λ“œ μ‚­μ œ)
DELETE FROM inbox
WHERE processed_at IS NOT NULL
  AND processed_at < NOW() - INTERVAL '30 days';

-- 2. νŒŒν‹°μ…”λ‹ 적용 (PostgreSQL μ˜ˆμ‹œ)
CREATE TABLE inbox (
    message_id VARCHAR(255) NOT NULL,
    message_type VARCHAR(100) NOT NULL,
    received_at TIMESTAMP NOT NULL DEFAULT NOW(),
    processed_at TIMESTAMP,
    payload JSONB,
    PRIMARY KEY (message_id, received_at)
) PARTITION BY RANGE (received_at);

-- 월별 νŒŒν‹°μ…˜ 생성
CREATE TABLE inbox_2025_01 PARTITION OF inbox
    FOR VALUES FROM ('2025-01-01') TO ('2025-02-01');

CREATE TABLE inbox_2025_02 PARTITION OF inbox
    FOR VALUES FROM ('2025-02-01') TO ('2025-03-01');

-- 였래된 νŒŒν‹°μ…˜ μ‚­μ œ (빠름)
DROP TABLE inbox_2024_12;

Performance optimization

// 1. Redisλ₯Ό μ΄μš©ν•œ 2단계 쀑볡 체크 (Hot Cache + Cold Storage)
class OptimizedInboxHandler {
  constructor(
    private redis: Redis,
    private db: DataSource,
    private inboxRepository: InboxRepository
  ) {}

  async handleMessage(messageId: string, handler: () => Promise<void>) {
    // Stage 1: Redis μΊμ‹œ 체크 (맀우 빠름)
    const cached = await this.redis.get(`inbox:${messageId}`);
    if (cached) {
      return; // Cache hit = 이미 처리됨
    }

    // Stage 2: DB 체크 (μΊμ‹œ 미슀 μ‹œμ—λ§Œ)
    const exists = await this.inboxRepository.isProcessed(messageId);
    if (exists) {
      // DB에 있으면 μΊμ‹œμ—λ„ μΆ”κ°€ (λ‹€μŒ 쀑볡 μ‹œ λΉ λ₯Έ 응닡)
      await this.redis.setex(`inbox:${messageId}`, 86400, '1'); // 24μ‹œκ°„ TTL
      return;
    }

    // Stage 3: νŠΈλžœμž­μ…˜ 처리
    await this.db.transaction(async (manager) => {
      await this.inboxRepository.recordMessage(manager, messageId, 'event', {});
      await handler();
    });

    // Stage 4: μΊμ‹œ κ°±μ‹ 
    await this.redis.setex(`inbox:${messageId}`, 86400, '1');
  }
}

// 2. Batch 처리둜 μ²˜λ¦¬λŸ‰ ν–₯상
class BatchInboxHandler {
  private batch: Array<{ messageId: string; handler: () => Promise<void> }> = [];
  private readonly BATCH_SIZE = 100;
  private readonly FLUSH_INTERVAL = 100; // ms

  async addMessage(messageId: string, handler: () => Promise<void>) {
    this.batch.push({ messageId, handler });

    if (this.batch.length >= this.BATCH_SIZE) {
      await this.flush();
    }
  }

  async flush() {
    if (this.batch.length === 0) return;

    const currentBatch = [...this.batch];
    this.batch = [];

    // 1. Batch둜 쀑볡 체크
    const messageIds = currentBatch.map(b => b.messageId);
    const existingIds = await this.checkBatch(messageIds);

    // 2. 쀑볡 μ•„λ‹Œ κ²ƒλ§Œ 처리
    const newMessages = currentBatch.filter(
      b => !existingIds.has(b.messageId)
    );

    // 3. Batch INSERT + κ°œλ³„ ν•Έλ“€λŸ¬ μ‹€ν–‰
    await this.processBatch(newMessages);
  }

  private async checkBatch(ids: string[]): Promise<Set<string>> {
    const results = await this.db.query(
      `SELECT message_id FROM inbox WHERE message_id = ANY($1)`,
      [ids]
    );
    return new Set(results.map((r: any) => r.message_id));
  }
}
⚠️ Distributed Transaction Caution If the Inbox table and the business table are in different databases, they cannot be combined into a single transaction. In that case, consider the Saga pattern or 2PC (Two-Phase Commit).

πŸ’¬ Practical Conversation Example

πŸ§‘β€πŸ’»
Junior Developer
When an exception occurs while a Kafka Consumer is processing a message, it is automatically retried, but by then the data has already been saved to the DB, so duplicate data is created. What should we do?
πŸ‘¨β€πŸ«
Senior developer
That's a typical At-Least-Once duplicate problem. You can apply the Inbox Pattern. Store the message's unique ID in the inbox table and check whether it already exists before processing. The key is to run the inbox INSERT and the business logic in the same transaction. That way you can prevent inconsistent states like "recorded but not processed."
πŸ§‘β€πŸ’»
Junior Developer
But if multiple Consumers are running, couldn't they process the same message at the same time? It seems both would check "not present" and try to INSERT simultaneously...
πŸ‘¨β€πŸ«
Senior developer
Good point! That's why you need to put a UNIQUE constraint on message_id. If they INSERT at the same time, one succeeds and the other raises a unique violation exception. You catch the exception, treat it as "already processed by another instance," and skip. This is the "try-insert-catch-duplicate" pattern instead of "check-then-act."
πŸ§‘β€πŸ’»
Junior Developer
After applying the Inbox Pattern, the inbox table is growing very fast. Millions of records pile up every day, so I'm worried about performance.
πŸ‘¨β€πŸ«
Senior developer
You need a table cleanup strategy. There are a few approaches:

1. Partitioning: create monthly partitions based on received_at and DROP old partitions
2. Batch deletion: delete records older than 30 days overnight after processing is complete
3. TTL tables: use a DB that supports automatic expiry, such as TimescaleDB or Cassandra

Lookup performance is O(1) because message_id is the Primary Key. Even if the table is large, looking up a specific ID is fast.
πŸ§‘β€πŸ’»
Junior Developer
Wouldn't it be faster to use Redis for duplicate checks?
πŸ‘¨β€πŸ«
Senior developer
Right, Redis is much faster. But using only Redis is problematic. Redis data disappears once the TTL expires, right? If the same message is redelivered after the TTL has passed, it will be processed twice.

So I recommend a two-stage strategy:
Stage 1: Redis check (fast path, filters out most duplicates here)
Stage 2: DB check on a Redis miss (slower but permanently guaranteed)

This way you get both speed and accuracy.
πŸ§‘β€πŸ’»
Junior Developer
Should the Outbox Pattern and the Inbox Pattern be used together?
πŸ‘¨β€πŸ«
Senior developer
If you need End-to-End reliability, you should use them together:

β€’ Outbox: guarantees at the Producer that "the message is always published" (prevents loss)
β€’ Inbox: guarantees at the Consumer that "the message is processed only once" (prevents duplicates)

The two solve different problems at opposite ends of the message pipeline. In domains where accuracy matters, such as payments or inventory, it is safer to apply both.

⚠️ Cautions and Tips

⚠️ Mind the Transaction Scope The Inbox INSERT and the business logic must be in the same transaction. If they are separated, an inconsistency occurs in which "only the Inbox is recorded and the business logic fails."
⚠️ Where to Generate the Message ID The Message ID must be generated by the Producer (sender). If it is generated by the Consumer, the same message is assigned different IDs, making duplicate prevention impossible.
⚠️ Beware of Depending on Kafka Offset Be careful when using the Kafka offset (topic-partition-offset) as the Message ID: if the offset is reset due to a Consumer Group change or topic re-creation, IDs can be duplicated.
πŸ’‘ Using the Processing Completion Time Adding a processed_at column lets you distinguish the "in progress" state. It is useful for identifying and reprocessing messages whose processing was left incomplete due to abnormal termination.
πŸ’‘ Benefits of Storing the Payload If you store the original message (payload) in the Inbox as well:
  • The original data can be checked during failure analysis
  • Messages that failed processing can be manually reprocessed
  • Serves as an audit log for event sourcing
πŸ’‘ Testing Tips Be sure to include concurrency tests when testing the Inbox Pattern:
  • Have N Consumers attempt to process the same message simultaneously
  • Verify that the business logic is executed exactly once
  • Confirm that UNIQUE constraint exceptions are handled correctly

πŸ”— Related Terms

πŸ“š Learn More