SNS 피드 시스템 인프라 아키텍처
결론
SNS 피드 시스템은 Hybrid Fan-out 모델을 사용하는 것이 가장 현실적입니다. 일반 사용자는 Fan-out on Write(Push)로 빠른 읽기를 제공하고, 팔로워가 많은 셀럽/인플루언서는 Fan-out on Read(Pull)로 쓰기 부하를 줄입니다.
핵심 인프라 구성:
- 캐싱: Redis (피드 데이터, Sorted Set 활용)
- 메시지 큐: Kafka (비동기 Fan-out 처리)
- 데이터베이스: NoSQL(Cassandra/DynamoDB) + RDBMS(PostgreSQL)
- 스토리지: Object Storage(S3) + CDN
Fan-out/Fan-in 패턴 이해
SNS 피드 시스템의 아키텍처를 이해하기 위해서는 먼저 Fan-out과 Fan-in 패턴의 개념을 이해해야 합니다.
용어의 유래
Wikipedia - Fan-out (software) (opens in a new tab)
"The term originally came from electronic components and defined the flow between their inputs and outputs."
Software Engineering Stack Exchange (opens in a new tab)
"In a visual diagram, output wires connecting to downstream nodes look like a hand-held paper fan, and those wires or number of wires is its fan-out."
이 용어는 전자공학에서 시작되었습니다. 하나의 출력에서 여러 연결선이 펼쳐지는 모습이 **부채(fan)**를 펼친 것처럼 보여서 "fan-out"이라고 부르게 되었습니다. 이후 소프트웨어 엔지니어링에서도 동일한 개념을 설명하기 위해 이 용어를 채택했습니다.
Fan-out 패턴 (1→N 분산)
System Design School - Fan-Out/Fan-In Pattern (opens in a new tab)
"Fan-out refers to a design pattern where a single input or event leads to multiple outputs or actions."
특징:
- 하나의 입력이 여러 출력으로 분산
- 병렬 처리 가능
- 작업 분배
시각화:
입력 (1)
│
[Fan-out]
↓ ↓ ↓
출력1 출력2 출력3 (N)SNS 피드에서의 예시:
사용자 A가 게시물 작성 (1)
↓
[Fan-out]
↓ ↓ ↓
팔로워1 팔로워2 팔로워3의 피드에 추가 (N)Fan-in 패턴 (N→1 집계)
Medium - The Fan-In pattern in Golang (opens in a new tab)
"The Fan-In pattern is a concurrency pattern where multiple input channels merge into a single output channel, enabling multiple concurrent tasks to send data into a unified stream."
특징:
- 여러 입력이 하나의 출력으로 집계
- 결과 수집 및 병합
- 데이터 집계
시각화:
입력1 입력2 입력3 (N)
↓ ↓ ↓
[Fan-in]
│
출력 (1)SNS 피드에서의 예시:
팔로잉1의 게시물 (N)
팔로잉2의 게시물 ↘
팔로잉3의 게시물 → [Fan-in] → 사용자의 피드 (1)SNS 피드 시스템에서의 적용
SNS 피드 시스템은 두 가지 방식으로 이 패턴들을 활용합니다:
1. Fan-out on Write (Push)
- Fan-out 패턴 사용
- 게시물 작성 시 모든 팔로워에게 분산
2. Fan-out on Read (Pull)
- 실제로는 Fan-in 패턴 사용
- 피드 조회 시 여러 소스를 집계
- "읽기 시점에 데이터를 Fan-out(분산 조회)"한다는 의미에서 이렇게 명명
3. Hybrid
- Fan-out과 Fan-in을 조합
구현 기술
AWS Blog - Messaging Fanout Pattern (opens in a new tab)
"The pattern is commonly implemented using pub/sub messaging systems like Amazon SNS/SQS, RabbitMQ, and other message brokers."
Fan-out 구현:
- Amazon SNS (Simple Notification Service)
- Apache Kafka (topics with multiple consumers)
- RabbitMQ (exchange)
Fan-in 구현:
- Amazon SQS (message aggregation)
- Shared storage (Redis, S3)
- Stream processing (Kafka Streams, Flink)
피드 생성 전략
1. Fan-out on Write (Push 모델)
새 게시물 작성 시 모든 팔로워의 피드에 미리 기록하는 방식입니다. 이 방식은 Fan-out 패턴을 사용합니다. 한 명의 사용자가 작성한 게시물(1)이 여러 팔로워(N)에게 분산되기 때문입니다.
GeeksforGeeks - Design Twitter (opens in a new tab)
"Tweets are immediately pushed to all followers' feeds, reducing read-time computation. Each user has their own 'inbox' inside the cache that stores the tweets to be displayed in its timeline."
장점:
- 읽기 속도가 매우 빠름 (이미 준비된 피드를 읽기만 함)
- 사용자 경험 향상 (즉시 피드 로딩)
단점:
- 쓰기 부하가 높음 (팔로워가 많을수록 기하급수적 증가)
- 저장공간 많이 필요
- 셀럽의 경우 Fan-out에 수 분 소요 가능
적합한 경우: 팔로워가 적거나 중간 규모의 일반 사용자
2. Fan-out on Read (Pull 모델)
사용자가 피드 요청 시 실시간으로 팔로잉 사용자들의 게시물을 조회해서 합성하는 방식입니다.
이름은 "Fan-out on Read"이지만, 실제로는 Fan-in 패턴을 사용합니다. 여러 팔로잉 사용자의 게시물(N)을 한 명의 사용자 피드(1)로 집계하기 때문입니다. "읽기 시점에 데이터를 Fan-out(분산 조회)"한다는 의미에서 이렇게 부릅니다.
AlgoMaster - Designing a Scalable News Feed System (opens in a new tab)
"Fan-out-on-read means the feed is computed at read time by querying posts from all followed users. Feeds are generated only when a user requests them, reducing database writes."
장점:
- 쓰기 부하가 낮음
- 저장공간 절약
- 셀럽도 빠르게 게시물 발행 가능
단점:
- 읽기 속도가 느림 (매번 계산 필요)
- 팔로잉이 많으면 성능 저하
- 읽기 작업 증가
적합한 경우: 팔로워가 매우 많은 셀럽/인플루언서
3. Hybrid 모델 (권장)
Fan-out과 Fan-in을 조합한 모델입니다. 일반 사용자는 Fan-out 패턴을, 셀럽은 Fan-in 패턴을 사용합니다.
Design a News Feed System (opens in a new tab)
"For users who has lots of followers, stop fanout write for their new posts. Instead, the followers fanout read the celebrities' updates. The hybrid model combines push and pull strategies—users with few followers use push, while high-follower users use pull, balancing read and write operations."
동작 방식:
- 일반 사용자 (팔로워 < 임계값): Fan-out on Write
- 셀럽 사용자 (팔로워 >= 임계값): Fan-out on Read
- 피드 조회 시: 두 소스를 timestamp 기준으로 병합
추가 최적화: 온라인 사용자에게만 Fan-out Hello Interview - Design Facebook's News Feed (opens in a new tab)
"When users send new posts, limit the fanout write to only their online followers."
인프라 아키텍처 계층
1. API Gateway / Load Balancer
- 기술: AWS ALB, NGINX, Kong
- 역할:
- Rate limiting (과도한 요청 방지)
- Authentication & Authorization
- Routing
2. Application Server
- 기술: ECS/EKS, Kubernetes
- 특징:
- Stateless 서버 (수평 확장 가능)
- Auto-scaling (CPU/메모리 기반)
- 피드 생성/조회 로직 처리
3. Caching 계층 (매우 중요)
JavaTechOnline - Social Media Feed System Design (opens in a new tab)
"News feed generation is quintessentially read-intensive - users check their feeds constantly but post rarely. This makes scaling reads essential through pre-computing feeds for active users, caching recent posts from followed users."
Redis 활용:
피드 캐시 구조 (Sorted Set)
Key: feed:{user_id}
Value: post_id
Score: created_at (timestamp)
명령어 예시:
ZADD feed:user123 1704067200 post456
ZREVRANGE feed:user123 0 19 # 최신 20개 조회캐싱 전략:
- Cache aside pattern 또는 Write through
- Hot data: 최근 24시간 피드만 캐시
- Cache warming: 인기 사용자 피드 미리 로드
- Multi-level cache: Application memory → Redis → Database
CDN: 이미지/동영상 등 미디어 콘텐츠 캐싱
4. Message Queue 계층
기술: Apache Kafka, RabbitMQ, AWS SQS
역할:
- 비동기 피드 생성 작업 (Fan-out 처리)
- 이벤트 기반 아키텍처로 느슨한 결합
- 높은 처리량 보장
Fan-out Worker 플로우:
1. Message Queue에서 "new post" 이벤트 수신
- event: {post_id, author_id, created_at}
2. author_id의 팔로워 목록 조회
3. 각 팔로워의 피드에 post_id 추가 (병렬 처리)
- Redis: ZADD feed:{follower_id} {timestamp} {post_id}
- DynamoDB: PutItem {user_id, post_id, created_at}
4. Dead letter queue로 실패 처리5. Database 계층
0xkishan - Designing a Scalable News Feed Architecture (opens in a new tab)
"Cassandra is known for its ability to scale horizontally, making it suitable for handling large volumes of posts and users. DynamoDB is designed for read-heavy applications."
NoSQL (Cassandra/DynamoDB): 피드 타임라인 데이터
Feed Table
- user_id (partition key)
- post_id (sort key / range key)
- created_at (timestamp)
- author_id왜 NoSQL?:
- 높은 쓰기 처리량 필요
- 사용자별로 독립적인 피드 (user_id로 파티셔닝)
- 시간순 정렬 (sort key)
- 수평 확장 용이
RDBMS (PostgreSQL/MySQL): 게시물, 사용자 메타데이터
Posts Table
- post_id (PK)
- author_id
- content
- created_at
- media_urls
- likes_count
- comments_countRead Replica: 읽기 부하 분산
Sharding: 사용자 ID 기반 데이터 파티셔닝 (Consistent Hashing)
6. Storage 계층
- Object Storage: S3, GCS (이미지, 동영상)
- CDN: CloudFront, Akamai (edge caching으로 지연시간 감소)
피드 생성 및 조회 플로우
A. 새 게시물 작성 시 (Fan-out on Write)
1. API Server: POST /posts 요청 수신
2. Posts 테이블에 게시물 저장
3. Message Queue에 "new post" 이벤트 발행
- event: {post_id, author_id, created_at}
4. 즉시 응답 반환 (202 Accepted)
5. Fan-out Worker (비동기):
a. author_id의 팔로워 목록 조회
b. 팔로워가 임계값 미만이면:
- 각 팔로워의 피드에 post_id 추가 (병렬 처리)
- Redis: ZADD feed:{follower_id} {timestamp} {post_id}
c. 팔로워가 임계값 이상이면:
- Fan-out 생략 (Pull 방식으로 조회)B. 피드 조회 시
1. API Server: GET /feed 요청 수신
2. Cache 확인 (Redis):
- ZREVRANGE feed:{user_id} 0 19 # 최신 20개
3. Cache Miss 시:
- DynamoDB Query: user_id로 조회, created_at 내림차순
4. 셀럽 게시물 병합 (Hybrid 모델):
- 팔로잉 중 셀럽 사용자 확인
- 셀럽의 최신 게시물 조회 (실시간)
- timestamp 기준으로 병합
5. Post 상세 정보 Batch 조회:
- Posts 테이블에서 post_ids로 조회
- 캐싱 레이어 활용
6. 응답 반환확장성 및 성능 최적화
1. Database Sharding
- User ID 기반 샤딩 (Consistent Hashing)
- 각 샤드는 독립적인 피드 데이터 관리
- Cross-shard query 최소화
2. Multi-level Caching
L1: Application memory (in-process cache)
↓ miss
L2: Redis cluster (distributed cache)
↓ miss
L3: Database- Cache warming: 인기 사용자 피드 미리 로드
- Cache invalidation: Write-through + TTL
3. Read/Write 분리
- Master-Replica 구조
- 읽기는 Replica로 분산
- 쓰기는 Master로 집중
- Replica lag 모니터링 중요
4. 비동기 처리
- Message Queue로 Fan-out 작업 분리
- Worker pool로 병렬 처리
- Dead letter queue로 실패 처리
5. Rate Limiting
- API Gateway 레벨에서 처리
- User-based, IP-based rate limiting
- 과도한 요청 방지
실제 기술 스택 예시
Option 1: AWS 기반 (클라우드 네이티브)
- Load Balancer: AWS ALB
- API Server: ECS/EKS (Docker containers)
- Cache: ElastiCache (Redis)
- Message Queue: Amazon SQS + SNS
- Database: Aurora (MySQL) + DynamoDB
- Storage: S3 + CloudFront (CDN)
- Monitoring: CloudWatchOption 2: 오픈소스 기반 (Kubernetes)
- Load Balancer: NGINX Ingress
- API Server: Kubernetes Pods
- Cache: Redis Cluster
- Message Queue: Apache Kafka
- Database: PostgreSQL (Patroni) + Cassandra
- Storage: MinIO + CDN
- Monitoring: Prometheus + GrafanaOption 3: Hybrid
- Cloud managed services + self-hosted critical components
- 예: AWS infrastructure + self-managed Kafka
모니터링 및 장애 대응
모니터링 지표
- API latency (p50, p95, p99)
- Cache hit ratio
- Queue depth (message backlog)
- Database connection pool usage
- Error rate
- Fan-out worker 처리 속도
고가용성 설계
- Multi-AZ/Region 배포
- Auto-scaling: CPU/메모리 기반
- Circuit breaker pattern: 장애 전파 방지
- Fallback mechanism: 캐시 실패 시 degraded mode
장애 시나리오 대응
Cache 장애:
- Database로 fallback (성능 저하 감수)
- 자동 복구 시 cache warming
Queue 장애:
- 임시 피드 누락 (eventual consistency)
- 자동 복구 시 backlog 재처리
Database 장애:
- Read replica failover
- Circuit breaker 작동
Worker 장애:
- Queue에 메시지 누적
- Auto-scaling으로 worker 증설
Data Consistency
- Eventual consistency 모델 채택
- 피드는 몇 초 지연 허용 (사용자 경험에 큰 영향 없음)
- Critical data (게시물, 사용자)는 Strong consistency
핵심 설계 결정 요약
- Fan-out 전략: Hybrid (일반/셀럽 구분, 팔로워 임계값 기반)
- Cache: Redis (Sorted Set으로 시간순 정렬 피드 저장)
- Queue: Kafka (높은 처리량, 메시지 순서 보장, 재처리 가능)
- NoSQL: Cassandra 또는 DynamoDB (쓰기 성능 우수, 수평 확장)
- RDBMS: PostgreSQL (복잡한 쿼리, ACID 보장, 메타데이터 관리)
- 비동기 처리: Fan-out 작업을 비동기로 처리해 빠른 응답
- Multi-level Caching: 읽기 부하 분산
출처
SNS 피드 아키텍처
- GeeksforGeeks - Design Twitter (opens in a new tab)
- AlgoMaster - Designing a Scalable News Feed System (opens in a new tab)
- Design a News Feed System (opens in a new tab)
- Hello Interview - Design Facebook's News Feed (opens in a new tab)
- JavaTechOnline - Social Media Feed System Design (opens in a new tab)
- 0xkishan - Designing a Scalable News Feed Architecture (opens in a new tab)
- System Design School - Design Twitter (opens in a new tab)
- Medium - Design Facebook | Twitter | Instagram news feed system (opens in a new tab)
- Stack Overflow - Twitter fanout design (opens in a new tab)
- NamasteDev - System Design of Twitter Feed (opens in a new tab)
Fan-out/Fan-in 패턴
- Wikipedia - Fan-out (software) (opens in a new tab)
- Software Engineering Stack Exchange - What is fan-out (opens in a new tab)
- System Design School - Fan-Out/Fan-In Pattern (opens in a new tab)
- Better Programming - Cloud Native Patterns: Fan-in and Fan-out (opens in a new tab)
- Medium - The Fan-In pattern in Golang (opens in a new tab)
- AWS Blog - Messaging Fanout Pattern (opens in a new tab)
- Java Design Patterns - Fan-Out Fan-In (opens in a new tab)