[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,89 +2,208 @@
|
||||
id: wiki-2026-0508-queue-management-systems
|
||||
title: Queue Management Systems
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [SYS-QUEUE-MGMT-001]
|
||||
aliases: [Message Queues, Job Queues, Task Queues]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [infrastructure, _systems, queue-Management, message-broker, rabbitmq, kafka, redis, asynchronous]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [queue, messaging, async, distributed-systems]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: python
|
||||
framework: rabbitmq-sqs-celery
|
||||
---
|
||||
|
||||
# Queue Management Systems (큐 관리 시스템)
|
||||
# Queue Management Systems
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "폭주하는 요청 앞에 '완충 지대(Buffer)'를 구축하여 시스템의 붕괴를 막고, 비동기적 흐름의 질서를 세워 전체적인 처리량(Throughput)을 극대화하라" — 작업을 즉시 처리하는 대신 대기열(Queue)에 보관했다가 순차적으로 처리함으로써 시스템 부하를 조절하고 서비스 간 결합도를 낮추는 인프라 관리 체계.
|
||||
## 매 한 줄
|
||||
> **"매 producer 와 consumer 매 decouple — 매 buffered, durable, retried"**. RabbitMQ / SQS / Redis / Celery / Sidekiq / Temporal — 매 async work 매 backbone. 매 2026 매 Temporal-style durable execution 매 mainstream.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Producer-Consumer Decoupling and Load Leveling" — 요청을 생성하는 쪽(Producer)과 처리하는 쪽(Consumer) 사이에 중계자(Queue/Broker)를 두어, 어느 한쪽의 속도 변화나 장애가 전체 시스템에 영향을 주지 않도록 격리하는 패턴.
|
||||
- **주요 도구 및 특성:**
|
||||
- **RabbitMQ:** 복잡한 라우팅과 메시지 보증이 필요한 업무에 적합.
|
||||
- **Apache Kafka:** 대규모 로그 및 실시간 스트림 데이터 처리에 최적화.
|
||||
- **Redis (Pub/Sub):** 초고속 인메모리 기반의 단순 메시지 전달.
|
||||
- **SQS (AWS):** 클라우드 기반의 관리형 큐 서비스.
|
||||
- **의의:** 서비스가 갑작스러운 트래픽 급증(Traffic Spike)에도 버틸 수 있게 하며, 무거운 작업(이미지 처리, 대량 메일 발송 등)을 백그라운드로 돌려 사용자 응답 속도를 높임.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 단순히 데이터를 순서대로 쌓아두는 '창고' 역할을 넘어, 이제는 데이터의 유실을 방지하는 영속성(Persistence) 보장과 분산 처리를 통한 수평적 확장성([[Scalability|Scalability]])이 큐 시스템 선택의 핵심 기준이 됨.
|
||||
- **정책 변화:** Antigravity 프로젝트는 에이전트의 대규모 지식 보강 작업 시, 개별 문서 보강 요청을 큐에 적재하고 가용 자원에 맞춰 병렬 처리함으로써 시스템 리소스의 효율을 극대화함.
|
||||
### 매 queue types
|
||||
- **FIFO point-to-point**: 매 single consumer per message (SQS, RabbitMQ direct).
|
||||
- **Pub-sub fanout**: 매 N consumers 모두 받음 (SNS, Redis pub/sub, RabbitMQ fanout).
|
||||
- **Priority**: 매 weighted consumption (RabbitMQ priority, Redis sorted set).
|
||||
- **Delayed**: 매 ETA-based (SQS DelaySeconds, Sidekiq scheduled).
|
||||
- **Dead letter**: 매 failed messages → DLQ.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Parallel-Computing-in-AI|Parallel-Computing-in-AI]], System-Design-for-AI-Scale, [[High-Availability-Systems|High-Availability-Systems]], Message-Queues-Foundations
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Queue-Management-Systems.md
|
||||
### 매 delivery guarantees
|
||||
- **At-most-once**: ack-on-delivery (Redis pub/sub).
|
||||
- **At-least-once**: ack-on-process — 매 default for most prod queues.
|
||||
- **Exactly-once**: 매 idempotent consumer + dedup (FIFO SQS, Kafka EOS).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 patterns
|
||||
- **Work queue**: 매 N workers, load-balanced.
|
||||
- **Competing consumers**: 매 same.
|
||||
- **Saga / orchestration**: 매 multi-step workflow (Temporal, Cadence).
|
||||
- **Outbox**: 매 transactional message dispatch.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 응용
|
||||
1. Background jobs (email, image resize, PDF gen).
|
||||
2. Microservice integration (order → fulfillment).
|
||||
3. Rate limiting / throttling (queue as buffer).
|
||||
4. Workflow orchestration (Temporal).
|
||||
5. Batch processing (SQS → Lambda fanout).
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### Celery (Python)
|
||||
```python
|
||||
from celery import Celery
|
||||
app = Celery("tasks", broker="redis://localhost:6379/0")
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
@app.task(bind=True, max_retries=3, retry_backoff=True)
|
||||
def send_email(self, to: str):
|
||||
try:
|
||||
smtp.send(to)
|
||||
except SMTPException as e:
|
||||
raise self.retry(exc=e, countdown=2 ** self.request.retries)
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
# Producer
|
||||
send_email.delay("alice@example.com")
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### RabbitMQ work queue
|
||||
```python
|
||||
import pika
|
||||
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
|
||||
ch = conn.channel()
|
||||
ch.queue_declare(queue="tasks", durable=True)
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
# Publisher
|
||||
ch.basic_publish(
|
||||
exchange="", routing_key="tasks", body=b"work",
|
||||
properties=pika.BasicProperties(delivery_mode=2), # persistent
|
||||
)
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
# Worker
|
||||
ch.basic_qos(prefetch_count=1)
|
||||
def callback(ch, method, props, body):
|
||||
process(body)
|
||||
ch.basic_ack(delivery_tag=method.delivery_tag)
|
||||
ch.basic_consume(queue="tasks", on_message_callback=callback)
|
||||
ch.start_consuming()
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### AWS SQS (boto3)
|
||||
```python
|
||||
import boto3
|
||||
sqs = boto3.client("sqs")
|
||||
url = sqs.get_queue_url(QueueName="jobs")["QueueUrl"]
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
# Send
|
||||
sqs.send_message(QueueUrl=url, MessageBody=json.dumps(payload),
|
||||
MessageGroupId="orders", MessageDeduplicationId=order_id) # FIFO
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
# Receive (long poll)
|
||||
resp = sqs.receive_message(QueueUrl=url, WaitTimeSeconds=20, MaxNumberOfMessages=10)
|
||||
for msg in resp.get("Messages", []):
|
||||
process(json.loads(msg["Body"]))
|
||||
sqs.delete_message(QueueUrl=url, ReceiptHandle=msg["ReceiptHandle"])
|
||||
```
|
||||
|
||||
### Redis Streams (consumer groups)
|
||||
```python
|
||||
import redis
|
||||
r = redis.Redis()
|
||||
r.xgroup_create("orders", "fulfillment", id="0", mkstream=True)
|
||||
|
||||
# Producer
|
||||
r.xadd("orders", {"id": "42", "total": "99"})
|
||||
|
||||
# Consumer
|
||||
while True:
|
||||
msgs = r.xreadgroup("fulfillment", "worker-1", {"orders": ">"}, count=10, block=5000)
|
||||
for stream, entries in msgs or []:
|
||||
for mid, data in entries:
|
||||
process(data)
|
||||
r.xack("orders", "fulfillment", mid)
|
||||
```
|
||||
|
||||
### Temporal workflow (durable execution)
|
||||
```python
|
||||
from temporalio import workflow, activity
|
||||
from datetime import timedelta
|
||||
|
||||
@activity.defn
|
||||
async def charge(card: str, amount: int) -> str:
|
||||
return payment_api.charge(card, amount)
|
||||
|
||||
@workflow.defn
|
||||
class OrderWorkflow:
|
||||
@workflow.run
|
||||
async def run(self, order: dict) -> str:
|
||||
tx = await workflow.execute_activity(
|
||||
charge, order["card"], order["total"],
|
||||
start_to_close_timeout=timedelta(seconds=30),
|
||||
retry_policy=RetryPolicy(maximum_attempts=5),
|
||||
)
|
||||
await workflow.execute_activity(ship, order, ...)
|
||||
return tx
|
||||
```
|
||||
|
||||
### Outbox pattern (transactional)
|
||||
```python
|
||||
def place_order(db, order):
|
||||
with db.transaction():
|
||||
db.execute("INSERT INTO orders ...", order)
|
||||
db.execute("INSERT INTO outbox (topic, payload) VALUES (?, ?)",
|
||||
"orders.created", json.dumps(order))
|
||||
# separate poller relays outbox → broker (at-least-once)
|
||||
```
|
||||
|
||||
### Dead letter queue handling
|
||||
```python
|
||||
# RabbitMQ DLX
|
||||
ch.queue_declare("tasks", arguments={
|
||||
"x-dead-letter-exchange": "dlx",
|
||||
"x-message-ttl": 60000,
|
||||
"x-max-retries": 3,
|
||||
})
|
||||
# DLQ consumer logs / alerts / manual replay
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Choice |
|
||||
|---|---|
|
||||
| 매 simple background jobs | Celery / Sidekiq / BullMQ |
|
||||
| 매 enterprise messaging | RabbitMQ |
|
||||
| 매 cloud-managed | SQS / Cloud Tasks |
|
||||
| 매 ordered + dedup | FIFO SQS |
|
||||
| 매 multi-step workflow | Temporal / Cadence / AWS Step Functions |
|
||||
| 매 high throughput log | Kafka (technically not a queue) |
|
||||
| 매 in-process | asyncio.Queue / channels |
|
||||
|
||||
**기본값**: 매 2026 매 durable workflow → Temporal. 매 simple jobs → BullMQ / Celery.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Messaging]] · [[Async Programming]]
|
||||
- 변형: [[Priority Queue]] · [[Dead Letter Queue]] · [[FIFO Queue]]
|
||||
- 응용: [[Background Jobs]] · [[Saga Pattern]] · [[Outbox Pattern]]
|
||||
- Adjacent: [[RabbitMQ]] · [[SQS]] · [[Celery]] · [[Temporal]] · [[Sidekiq]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 retry policy design, 매 DLQ analysis (cluster failure modes), 매 workflow code scaffold.
|
||||
**언제 X**: 매 throughput sizing — load test 직접.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **No idempotency**: 매 at-least-once + non-idempotent → duplicate side effects. 매 dedup key 필수.
|
||||
- **Infinite retry**: 매 poison message 매 forever — max attempts + DLQ.
|
||||
- **Unbounded queue**: 매 producer faster than consumer — OOM. 매 backpressure / drop oldest.
|
||||
- **Sync wait for queue result**: 매 anti-async — 매 callback / webhook / polling.
|
||||
- **Long-running task in queue with short visibility timeout**: 매 redelivered while still running — race.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (RabbitMQ docs; AWS SQS docs; Temporal docs 1.20+).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full queue systems entry with Temporal |
|
||||
|
||||
Reference in New Issue
Block a user