Folly Code Review
Meta Folly를 code review 시선으로 — performance-first 철학과 fbcode의 산물.
folly 89
Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
Meta(Facebook)가 production에서 검증한 Folly C++ 라이브러리를 code review의 시선으로 읽는다. performance-first 철학과 fbcode 환경의 산물을 14 Parts 63편으로 살펴본다.
Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
Folly의 출발점, 구성, std/Abseil과의 차별점 — Meta production에서 단련된 high-performance C++ 라이브러리.
Folly vs Abseil 철학 비교 — performance-first vs std-compatible
두 라이브러리의 설계 결정을 항목별로 비교 — 예외, 의존성, async 모델, ABI 정책.
Folly 빌드와 fbcode 환경 — monorepo의 그림자
Folly의 빌드 구조 — Meta 내부 fbcode/Buck, OSS는 CMake. 외부 빌드에서 마주치는 함정.
Folly API stability 정책 — 어떤 보장도 없다는 솔직함
Folly의 API/ABI 안정성 정책 — Meta의 입장과 외부 사용자가 따라야 할 전략.
Folly production validation 문화 — peta-scale에서 단련된 코드
Folly 컴포넌트가 Meta production scale에서 어떻게 검증되는가 — 외부 사용자가 신뢰해도 되는 부분과 주의할 부분.
folly::Future 분석 — std::future의 한계를 넘는 composable async
folly::Future가 std::future의 어떤 한계를 해결하는가 — continuation, executor binding, exception 전파.
folly::Promise·makeFuture — Future를 만드는 두 길
folly::Promise로 비동기 완료를 표현하고, makeFuture/makeSemiFuture로 이미 결정된 값을 Future 인터페이스에 올린다.
folly::SemiFuture vs Future — executor binding의 명시화
SemiFuture는 executor에 바인딩되지 않은 상태, Future는 바인딩 완료 상태. 이 구분이 라이브러리 API의 안전성을 만든다.
folly::Future thenValue·thenError·thenTry — continuation 체인 분석
Future continuation API의 세 변형 — 정상값, 예외, 통합 처리. .then은 deprecated.
folly::collect·collectAll·collectAny — fan-in 패턴 분석
여러 SemiFuture를 모으는 세 가지 의미 — 모두 성공, 모두 완료, 하나만 완료.
folly::Future retry·window·via — 제어 흐름 조합자
Future 조립의 제어 흐름 — 재시도, 동시성 윈도, executor 전환.
folly::fibers 분석 — M:N stackful coroutine
Folly fibers는 boost.context 기반 stackful coroutine. 동기 코드처럼 쓰고 비동기로 동작하는 M:N 모델.
folly::InlineExecutor — 호출자 thread에서 즉시 실행
InlineExecutor는 add()의 caller thread에서 callback을 그 자리에서 실행한다. 테스트와 단축 경로에 적합하지만 production hot path에는 위험하다.
folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
CPUThreadPoolExecutor는 CPU 집약 작업을 위한 thread pool. priority queue, blocking queue, thread factory를 조합한다.
folly::IOThreadPoolExecutor — libevent 기반 I/O pool
IOThreadPoolExecutor는 각 worker thread에 EventBase를 두어 libevent 기반 I/O와 timer를 처리한다.
folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
ManualExecutor는 schedule된 task를 자동 실행하지 않고 run()/drive() 호출 시점에만 진행한다. 비동기 코드의 단위 테스트에 결정성을 부여한다.
folly::EventBase 분석 — libevent 이벤트 루프의 핵심
EventBase는 libevent의 event_base를 wrap한 단일 thread event loop. file descriptor, timer, cross-thread message를 한 번에 처리한다.
folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
IOBuf는 ref-counted byte buffer chain. network 코드의 zero-copy 패턴을 표현하는 Folly의 핵심 자료구조다.
folly::IOBufQueue — chain의 push/pull 추상화
IOBufQueue는 IOBuf chain의 append/prepend/split을 효율적으로 관리한다. streaming codec과 framing layer의 표준 도구다.
folly::io::Cursor·RWCursor — chain 위의 stream
Cursor는 IOBuf chain을 단일 stream처럼 읽고 쓰는 추상화. endian-safe primitive read와 chain 자동 순회를 제공한다.
folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
IOBuf chain을 직접 writev/readv에 넘기고, splice/sendfile과 결합해 zero-copy 송수신 파이프라인을 구성한다.
folly::IOBuf shared semantics — clone·unshare·takeOwnership
IOBuf의 ref-count는 buffer share를 표현한다. clone/unshare/takeOwnership의 의미를 정확히 이해해야 zero-copy가 안전하다.
folly::FBString 분석 — SSO + COW 구현
FBString의 23-byte SSO와 Copy-on-Write, jemalloc 친화 레이아웃 — std::string 대체로서의 설계 결정.
folly의 fmt::format 통합 — 모던 포맷팅 채택
Folly가 fmt 라이브러리를 채택한 이유, formatter customization, sformat/format 차이.
folly::StringPiece — string_view 호환 분석
StringPiece의 역사적 배경, std::string_view와의 호환 layer, Range<const char*>로서의 일반화.
folly Join·Split utilities — 문자열 분해와 결합
folly::join과 folly::split의 구현, StringPiece 기반 zero-copy split, absl::StrSplit 비교.
folly::to·tryTo — text↔num 변환 분석
folly::to의 throw-on-error 변환, tryTo의 Expected 반환, 양방향 string/number 처리.
folly Conv Customization — 사용자 타입 지원
folly::to에 사용자 타입을 hook하기 — parseTo, toAppend ADL 확장.
folly Conv 성능 비교 — sprintf·stringstream 대비
folly::to의 성능 — lookup table itoa, SWAR atoi, sprintf/iostream과의 5-10배 차이.
folly::F14ValueMap vs std::unordered_map
F14ValueMap의 in-place value 저장과 std::unordered_map node-based의 차이, 성능과 reference 안정성.
folly::F14NodeMap — stable pointer가 필요할 때
F14NodeMap — value를 별도 heap node에 두어 pointer/reference 안정성을 보장하는 F14 변형.
folly::F14VectorMap — cache-friendly iteration
F14VectorMap — value를 contiguous vector에 두고 chunk에는 index만, 순회 cache-friendly.
folly::F14FastMap — auto-select 동작
F14FastMap — key/value 크기로 ValueMap과 VectorMap 중 자동 선택, 사용자 trade-off 제거.
folly F14 internals — SIMD probing 메커니즘
F14 chunk 구조와 SIMD probing — SSE2/AVX/NEON dispatch, H1/H2 hash split, 14-slot 선택 이유.
folly::small_vector — inline storage 분석
small_vector — N개까지 inline 저장, overflow는 heap, std::vector 호환 인터페이스.
folly::FixedString — compile-time string
FixedString — fixed capacity, fully constexpr 문자열 type. compile-time concat과 hash가 가능.
folly::AtomicHashMap — lock-free read 분석
AtomicHashMap — lock-free read, append-only insert, 큰 read-heavy 워크로드용 hash map.
folly::ConcurrentHashMap — sharded 동시 해시 맵
ConcurrentHashMap — sharded buckets + Hazard Pointer로 erase 포함 full thread-safe hash map.
folly::EvictingCacheMap — LRU 구현 분석
EvictingCacheMap — 고정 size 한도와 LRU eviction policy를 결합한 single-thread cache.
folly::Synchronized — lock wrapper 패턴
folly::Synchronized<T> — 데이터와 lock을 한 객체에 묶어 잠금 누락을 컴파일 타임에 막는다.
folly::SharedMutex 분석
folly::SharedMutex — std::shared_mutex보다 작고 빠른 reader-writer lock, fairness 정책 선택.
folly::Baton — one-shot wait 동기화
folly::Baton — 한 번 post, 한 번 wait의 경량 signal primitive. condition variable보다 가볍다.
folly::RWSpinLock 분석
folly::RWSpinLock — spin-only reader-writer lock, 매우 짧은 critical section에 SharedMutex보다 빠르다.
folly::PicoSpinLock — 1-byte spinlock
PicoSpinLock — integer type의 한 bit을 lock으로 사용. 객체 안에 lock을 끼워 넣어 메모리 절약.
folly::ProducerConsumerQueue — SPSC 큐 분석
Part 10-01: ProducerConsumerQueue — SPSC lock-free ring buffer. cache line padding, acquire/release만으로 RTT을 줄이는 패턴.
folly::MPMCQueue — multi-producer multi-consumer
Part 10-02: MPMCQueue — ticket 기반 lock-free 큐. CAS 없이 여러 producer/consumer를 안전하게 처리한다.
folly::UnboundedQueue — 동적 크기 lock-free
Part 10-03: UnboundedQueue — linked segment 기반 동적 크기 lock-free 큐. SPSC 모드에선 거의 무비용으로 성장한다.
folly::fibers::Channel — Go-like channel
Part 10-04: fibers::Channel — fiber 간 producer/consumer 채널. Go의 channel과 비슷한 sync 점.
folly::dynamic — JSON-like dynamic type 분석
Part 11-01: folly::dynamic — JSON-like 동적 타입. std::any와 무엇이 다른지, 왜 Meta는 별도 타입을 만들었는지.
folly JSON conversion — toJson·parseJson
Part 11-02: toJson / parseJson — folly::dynamic ↔ JSON 문자열. parse 옵션, 성능, schema-less 처리.
folly dynamic ↔ struct — manual marshaling
Part 11-03: dynamic을 strongly-typed struct로. type safety boundary를 어디에 그을지, marshaling 패턴 비교.
folly dynamic Visitor pattern — type별 분기
Part 11-04: dynamic을 type별로 처리하는 visitor 패턴. std::visit-like helper로 switch boilerplate를 줄인다.
folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
Part 12-01: Meyers singleton과 static 변수의 한계 — destruction order, fork safety, dependency 관리.
folly::SingletonVault 분석 — 등록·소멸·의존성
Part 12-02: SingletonVault — 모든 singleton의 통합 관리. 등록 순서, 의존성 그래프, eager/lazy 전략.
folly::Singleton try_get·try_get_fast — TLS-cached 접근
Part 12-03: try_get vs try_get_fast — TLS 캐시로 hot-path singleton 접근을 nanosecond 수준으로.
folly::ExceptionWrapper — type-erased exception holder
Part 13-01: ExceptionWrapper — exception을 throw 없이 옮기는 holder. async 콜백·thread 경계에서 핵심.
folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
Part 13-02: ScopeGuard / SCOPE_EXIT — RAII로 cleanup 보장. C에서 넘어온 코드 정리에 강력하다.
folly::Optional vs std::optional
Part 13-03: folly::Optional — std::optional와의 차이, 역사적 배경, monadic op과 std 호환.
folly::Function vs std::function
Part 13-04: folly::Function — move-only callable. unique_ptr capture, const-correctness, exec policy를 갖춘 std::function 대체.
folly::Lazy — 지연 초기화 wrapper
Part 13-05: folly::Lazy — once_flag/call_once 패턴을 type level로. 무거운 객체의 첫 사용까지 초기화 연기.
folly Meta 스타일 code review 패턴
Part 14-01: Meta(Facebook) 사내 code review 문화 — performance-first lens.
folly anti-patterns — 잘못 쓰면 std보다 느림
Part 14-02: Folly 오용 패턴 정리 — SemiFuture without via, fbstring small case, F14 잘못된 default, 등.
folly vs std 선택 기준 분석
Part 14-03: std/abseil/folly 선택 의사결정 가이드 — production scale, throughput, latency profile에 따른 분기.
folly::coro 개요 — production C++20 코루틴 어댑터
folly::coro의 위치 — std 코루틴 위에 Task/AsyncGenerator/Mutex를 쌓아 production async를 가능하게 한 이유.
folly::coro::Task — lazy single-shot 코루틴
Task<T>의 lazy start, executor 바인딩, scheduleOn, 값/예외 전파 — production async의 기본 단위.
folly::coro::AsyncGenerator — 비동기 스트림
AsyncGenerator<T>의 pull-based 모델, co_yield, for co_await — 비동기 iterator의 표준 후보 패턴.
folly coro blockingWait·collectAll — 동기 경계와 fan-in
blockingWait, collectAll, collectAllRange — sync 경계 연결과 병렬 합성, deadlock 회피 규칙.
folly::coro::Baton·Mutex — 코루틴-aware 동기화
coro::Baton과 coro::Mutex — thread를 block하지 않고 코루틴만 suspend하는 동기화 프리미티브.
folly::Expected — 결과 또는 오류
Expected<T, E>의 monadic API, std::expected와의 차이, absl::StatusOr와의 비교 — 예외 없는 에러 표현.
folly::Try — Future 결과 wrapper
Try<T>의 세 상태 (value/exception/empty), Future 내부에서의 역할, exception_wrapper와의 관계.
folly::Try vs Expected 선택 기준
언제 Try, 언제 Expected — 비동기 결과 슬롯과 도메인 오류 표현의 명확한 분리.
folly::Range — 일반 iterator pair
Range<Iter>의 설계, StringPiece의 일반화, std::span / std::string_view와의 관계.
folly::Uri — URL 파서
Uri의 RFC 3986 파싱, query string 추출, scheme/host/path 분해 — 표준에 없는 빈자리.
folly Fingerprint64·128 — 분산 hash
Fingerprint의 polynomial Rabin-Karp 기반 hash — sharding, dedup, content addressing.
folly SpookyHashV2 — fast non-crypto hash
SpookyHashV2의 ARX (Add/Rotate/Xor) 기반 빠른 hash — F14의 hasher 기본 후보.
folly::Init — main() 부트스트랩
folly::Init의 역할 — gflags 파싱, signal handler, glog 설정, exit handler 통합.
folly::Indestructible — global lifetime 패턴
Indestructible<T>의 동기 — Meyers singleton의 static deinitialization 함정과 그 회피.
folly::MicroLock — 1-byte 락
MicroLock의 1-byte 표현 — futex 기반 lock으로 std::mutex(40+ byte)의 메모리 비용 회피.
folly::MicroSpinLock — 가장 좁은 spin lock
MicroSpinLock의 1-byte 표현, sleep 없는 순수 spin — 짧은 critical section 전용.
folly::format — legacy formatter 분석
folly::format의 historical 위치, fmt와의 관계, std::format으로의 마이그레이션 경로.
folly::demangle — typeid 디망글링
folly::demangle의 역할 — C++ mangled name을 읽기 쉬운 형식으로, crash log와 typeid 출력에 필수.
folly::DynamicConverter — dynamic ↔ struct
DynamicConverter의 역할 — folly::dynamic과 user struct 사이 boilerplate 없는 양방향 변환.
folly::RecordIO — append-only 로그 파일 포맷
RecordIO의 frame 포맷, checksum, mid-file 복구 — append-only log 파일의 표준 패턴.
folly::io::Compression — zstd·lz4·snappy wrapper
folly::io::Codec — IOBuf 기반 통합 compression API. zstd/lz4/snappy를 같은 인터페이스로.
folly::AsyncIO — io_uring·Linux AIO
folly::AsyncIO와 IoUringBackend — kernel async disk I/O, callback과 coroutine 통합.
folly::CancellationToken — 코루틴·Future 취소 전파
CancellationSource/Token의 전파 모델 — coroutine·Future·callback 트리에서 협력적 취소.
folly::observer — hot config의 atomic refresh
folly::observer — read mostly 값의 atomic refresh, hot config·feature flag·LB weight 같은 패턴의 표준.
fbcode 패턴 모음 — folly 사용의 실전
Meta fbcode 코드 리뷰에서 반복적으로 등장하는 folly 사용 패턴 — overview + 시리즈 마무리.