fbcode 패턴 모음 — folly 사용의 실전
한 줄 요약: 21 parts 88 chapters를 통과한 folly 시리즈의 마지막. fbcode 코드 리뷰에서 반복적으로 등장하는 folly 사용 패턴을 한 자리에 정리한다.
#시리즈 마무리
이 시리즈는 folly를 다음 14 파트로 시작해 7 파트를 추가했다.
- Part 1: 개요 / 철학 / build
- Part 2: Future / Promise
- Part 3: Executors
- Part 4: IOBuf / Cursor
- Part 5: String 계열
- Part 6: Conv
- Part 7: F14 hash maps
- Part 8: 컨테이너
- Part 9: 동기화 primitive
- Part 10: Queue
- Part 11: dynamic / JSON
- Part 12: Singleton
- Part 13: Utility
- Part 14: 코드 리뷰 가이드
- Part 15: coro
- Part 16: Expected / Try
- Part 17: Range / Uri / Hash
- Part 18: Init / Indestructible / MicroLock
- Part 19: Format / Demangle / DynamicConverter
- Part 20: RecordIO / Compression / AsyncIO / Cancellation
- Part 21: Observer / 패턴 모음
여기서는 시리즈 내내 반복된 생산 코드의 folly 패턴을 챕터 횡단으로 묶는다.
#패턴 1 — 함수 인자는 view, 반환은 owning
// Goodvoid Process(folly::StringPiece s);folly::fbstring Build();
std::unique_ptr<folly::IOBuf> Encode(folly::ByteRange data);
// Badvoid Process(const std::string& s); // 호출자가 std::string 강요fbstring* Build(); // ownership 모호StringPiece / ByteRange / Range<Iter>로 받아 임의 view를 허용. 반환은 ownership이 명확한 type.
#패턴 2 — Future 체인 vs 코루틴
// Future style (legacy)folly::SemiFuture<Result> Process(Input x) { return Step1(x) .via(executor) .thenValue([](S1 s1) { return Step2(s1); }) .thenValue([](S2 s2) { return Step3(s2); });}
// Coroutine style (preferred for new code)folly::coro::Task<Result> Process(Input x) { auto s1 = co_await Step1(x); auto s2 = co_await Step2(s1); co_return co_await Step3(s2);}새 코드는 코루틴. 두 모델이 양방향 변환 가능해 점진적 마이그레이션.
#패턴 3 — Synchronized 우선, raw mutex는 예외
// Goodfolly::Synchronized<std::vector<Item>> items_;
void Add(Item x) { items_.wlock()->push_back(std::move(x));}
size_t Size() const { return items_.rlock()->size();}
// Badstd::mutex mu_;std::vector<Item> items_;// data와 mutex가 분리 — lock 누락 riskSynchronized<T>로 데이터와 lock을 한 객체에. lock 없이 접근하는 코드 경로가 컴파일러로 막힘.
#패턴 4 — F14는 기본 hash map
folly::F14FastMap<std::string, int> m; // value-stable, fastfolly::F14NodeMap<Key, BigValue> nm; // pointer-stablefolly::F14ValueMap<Key, SmallValue> vm; // value-inline (smaller)folly::F14VectorMap<Key, Value> ordered; // iteration order = insertionstd::unordered_map 대신 F14가 기본. variant 선택은 value 크기와 pointer stability.
#패턴 5 — Indestructible로 global
Foo& GetFoo() { static folly::Indestructible<Foo> instance; return *instance;}Meyers singleton의 static deinit order 위험을 회피.
#패턴 6 — Init은 main() 첫 줄
int main(int argc, char* argv[]) { folly::Init init(&argc, &argv); RunServer();}gflags, glog, signal handler 일괄 init. fbcode 거의 모든 binary 표준.
#패턴 7 — JSON은 dynamic + parseJson
auto d = folly::parseJson(text);auto cfg = folly::convertTo<Config>(d); // DynamicConverter// 또는auto host = d["host"].asString();dynamic이 type-erased, struct로 변환은 traits 한 번.
#패턴 8 — to 한 줄 변환
auto n = folly::to<int>("42");auto s = folly::to<std::string>(42);auto fp = folly::to<double>(s);std::to_string / std::stoi의 통합. 잘못된 입력에 throw, tryTo<T>는 Expected.
#패턴 9 — Cancellation을 처음부터
folly::coro::Task<Result> Compute(folly::CancellationToken ct) { // 매 step마다 check if (ct.isCancellationRequested()) throw folly::OperationCancelled{}; // ...}긴 작업은 처음부터 cancel-aware. 나중에 추가하기 어렵다.
#패턴 10 — Observer로 hot config
class Service { folly::observer::Observer<Config> cfg_; public: void Handle() { auto snap = cfg_.getSnapshot(); if (snap->featureEnabled) { ... } }};read-heavy 값은 observer. lock-free atomic load.
#패턴 11 — Try/thenTry로 예외 처리
compute() .thenTry([](folly::Try<int>&& t) { if (t.hasException()) return -1; return *t * 2; });
// 코루틴auto t = co_await folly::coro::co_awaitTry(MaybeFails());if (t.hasException()) { /* ... */ }throw가 normal control flow면 Try로 받아 비용 절감.
#패턴 12 — StringPiece는 함수 경계 표준
void Parse(folly::StringPiece s); // std::string, const char*, std::string_view 모두 받음API boundary의 받는 자리가 항상 view.
#패턴 13 — IOBuf chain은 직접 만들지 말 것
folly::IOBufQueue q{folly::IOBufQueue::cacheChainLength()};q.append(buf1);q.append(buf2);auto out = q.move();수동 next chain 연결은 깨지기 쉽다. IOBufQueue가 표준.
#패턴 14 — fbstring은 boundary에서 변환
folly::fbstring fs = Build();std::string sd = fs.toStdString(); // boundary 한 번
// 또는 처음부터 std::string 사용std::string Build();fbcode 내부는 fbstring, 외부 API와의 경계만 std::string으로 변환.
#패턴 15 — Conv는 ASCII fast path 활용
auto n = folly::to<int>("12345"); // SIMD-friendly fast path큰 batch parsing에 stl 보다 결정적으로 빠름.
#코드 리뷰 빈도 높은 지적
다음은 fbcode PR review에서 가장 자주 받는 코멘트 모음.
- “
std::string&로 받지 말고folly::StringPiece또는std::string_view로.” - “raw
std::mutex+ 데이터 대신folly::Synchronized<T>.” - “
std::unordered_map은folly::F14FastMap으로 — 성능 4-5x.” - “
std::shared_ptr을 매 호출 복사하지 말고folly::observer모델.” - “
Future::then은 deprecated.thenValue+thenError또는 코루틴.” - “새 코드는 코루틴
folly::coro::Task로 — Future chain은 legacy.” - “global mutex는
folly::Indestructible로 wrap — deinit order fiasco 회피.” - “hot path에
folly::format대신fmt::format또는std::format.” - “
std::async로 disk I/O 던지지 말고folly::AsyncIO(io_uring).” - “
OperationCancelled잡고 silent return하지 말 것 — propagate.”
#일반 가이드 — folly를 적게 쓰기
표준이 따라잡은 자리는 표준이 옳다.
folly::Optional→std::optionalfolly::Function→std::move_only_function(C++23) 또는std::functionfolly::StringPiece→std::string_view(대부분 자리)folly::format→std::format(C++20+)
folly가 우위인 자리만 folly:
- 코루틴 (folly::coro)
- F14 hash map
- Synchronized
- IOBuf
- 동시성 자료구조 (MPMCQueue, ConcurrentHashMap)
- Future chain (legacy migration)
- AsyncIO / io_uring wrapper
#시리즈를 마치며
folly는 프로덕션 C++의 잃어버린 절반이다. 표준이 채우지 못한 자리에서 Meta가 10년 넘게 쌓아온 추상. 이 시리즈를 통과한 독자는 다음을 얻었기를 바란다.
- 각 folly 구성요소의 왜 존재하는가.
- 표준/abseil과의 trade-off.
- 코드 리뷰에서 무엇을 살펴봐야 하는가.
- 안티패턴과 그 회피.
새 코드는 가능하면 표준, 표준이 부족한 자리는 folly. 그 경계 인식이 이 시리즈의 가장 큰 가치다.
#관련 항목
Folly Code Review · 89 of 89
- 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
- 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
- 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
- 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
- 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
- 6 Folly production validation 문화 — peta-scale에서 단련된 코드
- 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
- 8 folly::Promise·makeFuture — Future를 만드는 두 길
- 9 folly::SemiFuture vs Future — executor binding의 명시화
- 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
- 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
- 12 folly::Future retry·window·via — 제어 흐름 조합자
- 13 folly::fibers 분석 — M:N stackful coroutine
- 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
- 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
- 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
- 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
- 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
- 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
- 20 folly::IOBufQueue — chain의 push/pull 추상화
- 21 folly::io::Cursor·RWCursor — chain 위의 stream
- 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
- 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
- 24 folly::FBString 분석 — SSO + COW 구현
- 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
- 26 folly::StringPiece — string_view 호환 분석
- 27 folly Join·Split utilities — 문자열 분해와 결합
- 28 folly::to·tryTo — text↔num 변환 분석
- 29 folly Conv Customization — 사용자 타입 지원
- 30 folly Conv 성능 비교 — sprintf·stringstream 대비
- 31 folly::F14ValueMap vs std::unordered_map
- 32 folly::F14NodeMap — stable pointer가 필요할 때
- 33 folly::F14VectorMap — cache-friendly iteration
- 34 folly::F14FastMap — auto-select 동작
- 35 folly F14 internals — SIMD probing 메커니즘
- 36 folly::small_vector — inline storage 분석
- 37 folly::FixedString — compile-time string
- 38 folly::AtomicHashMap — lock-free read 분석
- 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
- 40 folly::EvictingCacheMap — LRU 구현 분석
- 41 folly::Synchronized — lock wrapper 패턴
- 42 folly::SharedMutex 분석
- 43 folly::Baton — one-shot wait 동기화
- 44 folly::RWSpinLock 분석
- 45 folly::PicoSpinLock — 1-byte spinlock
- 46 folly::ProducerConsumerQueue — SPSC 큐 분석
- 47 folly::MPMCQueue — multi-producer multi-consumer
- 48 folly::UnboundedQueue — 동적 크기 lock-free
- 49 folly::fibers::Channel — Go-like channel
- 50 folly::dynamic — JSON-like dynamic type 분석
- 51 folly JSON conversion — toJson·parseJson
- 52 folly dynamic ↔ struct — manual marshaling
- 53 folly dynamic Visitor pattern — type별 분기
- 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
- 55 folly::SingletonVault 분석 — 등록·소멸·의존성
- 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
- 57 folly::ExceptionWrapper — type-erased exception holder
- 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
- 59 folly::Optional vs std::optional
- 60 folly::Function vs std::function
- 61 folly::Lazy — 지연 초기화 wrapper
- 62 folly Meta 스타일 code review 패턴
- 63 folly anti-patterns — 잘못 쓰면 std보다 느림
- 64 folly vs std 선택 기준 분석
- 65 folly::coro 개요 — production C++20 코루틴 어댑터
- 66 folly::coro::Task — lazy single-shot 코루틴
- 67 folly::coro::AsyncGenerator — 비동기 스트림
- 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
- 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
- 70 folly::Expected — 결과 또는 오류
- 71 folly::Try — Future 결과 wrapper
- 72 folly::Try vs Expected 선택 기준
- 73 folly::Range — 일반 iterator pair
- 74 folly::Uri — URL 파서
- 75 folly Fingerprint64·128 — 분산 hash
- 76 folly SpookyHashV2 — fast non-crypto hash
- 77 folly::Init — main() 부트스트랩
- 78 folly::Indestructible — global lifetime 패턴
- 79 folly::MicroLock — 1-byte 락
- 80 folly::MicroSpinLock — 가장 좁은 spin lock
- 81 folly::format — legacy formatter 분석
- 82 folly::demangle — typeid 디망글링
- 83 folly::DynamicConverter — dynamic ↔ struct
- 84 folly::RecordIO — append-only 로그 파일 포맷
- 85 folly::io::Compression — zstd·lz4·snappy wrapper
- 86 folly::AsyncIO — io_uring·Linux AIO
- 87 folly::CancellationToken — 코루틴·Future 취소 전파
- 88 folly::observer — hot config의 atomic refresh
- 89 fbcode 패턴 모음 — folly 사용의 실전
관련 글
Folly 빌드와 fbcode 환경 — monorepo의 그림자
Folly의 빌드 구조 — Meta 내부 fbcode/Buck, OSS는 CMake. 외부 빌드에서 마주치는 함정.
같은 시리즈에서 이어 읽기
folly::observer — hot config의 atomic refresh
folly::observer — read mostly 값의 atomic refresh, hot config·feature flag·LB weight 같은 패턴의 표준.
같은 시리즈에서 이어 읽기
folly::CancellationToken — 코루틴·Future 취소 전파
CancellationSource/Token의 전파 모델 — coroutine·Future·callback 트리에서 협력적 취소.
같은 시리즈에서 이어 읽기