본문으로 건너뛰기
Folly Code Review · 1/89

Folly 개요 — Meta가 production에서 검증한 utility 모음 분석

· Hawk · 5분 읽기

한 줄 요약: Folly는 Meta의 fbcode monorepo에서 자라난 performance-first C++ 라이브러리다. std가 채우지 못한 자리를 마이크로초 단위로 최적화된 구현으로 메운다.

#동기 — std는 왜 부족한가

C++ 표준 라이브러리는 신중하다. 표준화 위원회의 합의를 거치고, 모든 처리계가 구현 가능해야 하며, ABI 안정성을 보장해야 한다. 그 신중함은 안전망인 동시에 한계다.

Meta는 다른 제약을 가진다. 수십억 사용자의 요청을 처리해야 하고, 마이크로초가 데이터센터 수십 대 분량의 비용 차이로 이어진다. fbcode monorepo는 단일 빌드 시스템과 단일 toolchain을 강제하므로 ABI 호환성을 외부와 맞출 필요도 없다. 이 환경에서 Folly가 자라났다.

측면표준 라이브러리Folly
ABI보수적 안정빌드마다 변경 가능
구현범용워크로드 specific 최적화
예외회피 옵션적극 활용
의존성독립적jemalloc/glog/Boost 의존
거버넌스표준 위원회 합의Meta 내부 합의 + OSS 공개

Folly는 그 결과물이다. fbstring은 24바이트 SSO와 __builtin_expect 기반 분기 힌트로 std::string보다 빠르고, F14 hashmap은 SIMD 16-way probing으로 std::unordered_map을 두 배 이상 앞선다. fbvector는 jemalloc의 realloc()을 직접 호출해 메모리를 in-place로 확장한다.

#구성 한눈에

Folly의 헤더는 카테고리별로 정리된다.

헤더역할
FBString.h, FBVector.hstd 컨테이너 대체
container/F14*.hSIMD hashmap (Swiss table류)
small_vector.h, sorted_vector.hsmall/sorted vector
futures/Future/Promise — std::future 대체
executors/CPU/IO ThreadPool, EventBase
io/IOBuf.h, IOBufQueue.hzero-copy network buffer
synchronization/Baton, Latch, DistributedMutex
concurrency/ConcurrentHashMap, MPMCQueue
fibers/M
stackful coroutine
dynamic.h, json.h동적 타입 + JSON
Format.h, Conv.h빠른 포맷팅/변환
Optional.h, Expected.h, Try.herror handling
Singleton.h안전한 leak-free singleton
ScopeGuard.hRAII utility

각 컴포넌트는 그 자체로 시리즈 한 편이 될 만한 깊이를 가진다.

#간단한 사용 예

#include <folly/FBString.h>
#include <folly/futures/Future.h>
#include <folly/executors/CPUThreadPoolExecutor.h>
folly::CPUThreadPoolExecutor pool(4);
folly::SemiFuture<int> compute() {
return folly::makeSemiFuture(42);
}
int main() {
auto result = compute()
.via(&pool)
.thenValue([](int x) { return x * 2; })
.thenValue([](int x) { return std::to_string(x); })
.get(); // "84"
}

Future continuation, executor binding, 동기 대기까지 한 줄로 표현된다. std::future로는 어색한 패턴이 Folly에서는 자연스럽다.

#설계 철학

#성능 우선

마이크로 최적화를 주저하지 않는다. fbstring의 23바이트 SSO, F14의 SIMD probing, IOBuf의 ref-counted chain은 모두 캐시 라인과 분기 예측을 의식한 결과다. 표준 라이브러리가 “범용성을 위한 평균”을 노린다면 Folly는 “워크로드의 peak”를 노린다.

#예외 적극 활용

Folly는 예외를 회피하지 않는다. folly::Promise::setException(folly::exception_wrapper), folly::Future::thenError<E>처럼 예외를 1급 시민으로 취급한다. 다만 hot path에서는 Try<T>Expected<T, E>로 분기를 명시적으로 다룬다.

folly::Expected<int, std::string> safeDivide(int a, int b) {
if (b == 0) return folly::makeUnexpected("div by zero");
return a / b;
}

#의존성 수용

Boost, glog, gflags, jemalloc, OpenSSL, zstd, double-conversion, fmt까지 끌어들인다. 통합 비용이 크지만 재발명하지 않는다. Abseil이 의존성을 최소화하는 것과 정반대의 입장이다.

#std vs Folly 비교 한 장

영역stdFolly차별점
stringstd::stringfolly::fbstring23B SSO, COW
vectorstd::vectorfolly::fbvectorjemalloc realloc, 50% growth
hashmapstd::unordered_mapfolly::F14*MapSIMD probing
futurestd::futurefolly::Futurecontinuation, executor
optionalstd::optionalfolly::OptionalC++14 호환
variantstd::variantfolly::dynamicJSON-friendly
string formattingstd::format (C++20)folly::format, fmt::formatC++14 호환

표준이 도착하면 Folly는 점진적으로 표준을 활용한다. folly::Optional은 내부에서 std::optional로 대체되는 중이고, folly::format은 fmt 통합으로 이동했다.

#Abseil과의 차이

같은 utility 라이브러리지만 출발점이 다르다.

항목Abseil (Google)Folly (Meta)
철학std 보완 (Living at Head)std 능가 (performance peak)
예외사용 금지적극 사용
의존성최소 (자체 완결)Boost/glog/jemalloc 다수
빌드Bazel + CMakeCMake (외부) / Buck (내부)
Async 모델거의 없음Future + Executor + Fiber
Zero-copy I/O없음IOBuf 체계
ABI동일 빌드 내 보장어떤 보장도 없음

핵심은 “Folly가 가진 것Abseil이 안 가진 것”이라는 점이다. Future/Executor/IOBuf/Fiber는 Abseil에 없다. 반대로 Abseil의 Status/StatusOr는 Folly에는 Expected로 일부만 대응한다.

#코드 리뷰 포인트

  • 표준에 동일 기능이 있는가? C++20 이후로 std::format, std::span, std::expected, std::optional이 들어왔다. 신규 코드는 표준을 우선 검토하고, Folly가 필요한 명확한 이유가 있을 때만 도입한다.
  • executor 바인딩이 명시적인가? Future continuation은 어떤 executor 위에서 도는지 코드로 추적 가능해야 한다. .via(&pool) 누락은 흔한 버그다.
  • 예외 정책이 일관적인가? 같은 프로젝트 안에서 Folly Future의 예외 전파와 Expected 사용이 섞이면 디버깅이 어렵다.
  • 의존성 비용을 알고 있는가? Folly 한 헤더가 Boost/glog/jemalloc까지 끌고 들어온다.

#자주 보는 안티패턴

// 1. SemiFuture를 그대로 .get() — deadlock 위험
auto v = compute().get(); // executor 미바인딩 + 동기 대기
// 2. Future를 멤버로 저장
class Worker {
folly::Future<int> f_; // continuation 체인이 살아있어야 함
};
// 3. Boost 충돌
// folly/Optional.h가 boost/optional.h와 transitive include 충돌

#정리

  • Folly는 Meta fbcode의 성능 요구를 충족하기 위해 자라난 utility 라이브러리다.
  • 성능 우선, 예외 활용, 의존성 수용 세 축으로 std/Abseil과 구분된다.
  • Future/Executor/IOBuf/Fiber는 Abseil이 갖지 못한 Folly 고유의 강점이다.
  • ABI를 보장하지 않으므로 빌드 시 반드시 단일 toolchain으로 정적 링크한다.
  • C++20 이후 표준이 따라잡은 영역은 표준을 우선 쓰고, Folly는 남은 격차에만 도입한다.

#다음 편

Part 1-02: Folly vs Abseil 철학 차이에서 두 라이브러리의 설계 결정을 항목별로 비교한다.

#관련 항목

Folly Code Review · 2 of 89

  1. 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
  2. 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
  3. 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
  4. 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
  5. 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
  6. 6 Folly production validation 문화 — peta-scale에서 단련된 코드
  7. 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
  8. 8 folly::Promise·makeFuture — Future를 만드는 두 길
  9. 9 folly::SemiFuture vs Future — executor binding의 명시화
  10. 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
  11. 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
  12. 12 folly::Future retry·window·via — 제어 흐름 조합자
  13. 13 folly::fibers 분석 — M:N stackful coroutine
  14. 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
  15. 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
  16. 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
  17. 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
  18. 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
  19. 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
  20. 20 folly::IOBufQueue — chain의 push/pull 추상화
  21. 21 folly::io::Cursor·RWCursor — chain 위의 stream
  22. 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
  23. 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
  24. 24 folly::FBString 분석 — SSO + COW 구현
  25. 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
  26. 26 folly::StringPiece — string_view 호환 분석
  27. 27 folly Join·Split utilities — 문자열 분해와 결합
  28. 28 folly::to·tryTo — text↔num 변환 분석
  29. 29 folly Conv Customization — 사용자 타입 지원
  30. 30 folly Conv 성능 비교 — sprintf·stringstream 대비
  31. 31 folly::F14ValueMap vs std::unordered_map
  32. 32 folly::F14NodeMap — stable pointer가 필요할 때
  33. 33 folly::F14VectorMap — cache-friendly iteration
  34. 34 folly::F14FastMap — auto-select 동작
  35. 35 folly F14 internals — SIMD probing 메커니즘
  36. 36 folly::small_vector — inline storage 분석
  37. 37 folly::FixedString — compile-time string
  38. 38 folly::AtomicHashMap — lock-free read 분석
  39. 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
  40. 40 folly::EvictingCacheMap — LRU 구현 분석
  41. 41 folly::Synchronized — lock wrapper 패턴
  42. 42 folly::SharedMutex 분석
  43. 43 folly::Baton — one-shot wait 동기화
  44. 44 folly::RWSpinLock 분석
  45. 45 folly::PicoSpinLock — 1-byte spinlock
  46. 46 folly::ProducerConsumerQueue — SPSC 큐 분석
  47. 47 folly::MPMCQueue — multi-producer multi-consumer
  48. 48 folly::UnboundedQueue — 동적 크기 lock-free
  49. 49 folly::fibers::Channel — Go-like channel
  50. 50 folly::dynamic — JSON-like dynamic type 분석
  51. 51 folly JSON conversion — toJson·parseJson
  52. 52 folly dynamic ↔ struct — manual marshaling
  53. 53 folly dynamic Visitor pattern — type별 분기
  54. 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
  55. 55 folly::SingletonVault 분석 — 등록·소멸·의존성
  56. 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
  57. 57 folly::ExceptionWrapper — type-erased exception holder
  58. 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
  59. 59 folly::Optional vs std::optional
  60. 60 folly::Function vs std::function
  61. 61 folly::Lazy — 지연 초기화 wrapper
  62. 62 folly Meta 스타일 code review 패턴
  63. 63 folly anti-patterns — 잘못 쓰면 std보다 느림
  64. 64 folly vs std 선택 기준 분석
  65. 65 folly::coro 개요 — production C++20 코루틴 어댑터
  66. 66 folly::coro::Task — lazy single-shot 코루틴
  67. 67 folly::coro::AsyncGenerator — 비동기 스트림
  68. 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
  69. 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
  70. 70 folly::Expected — 결과 또는 오류
  71. 71 folly::Try — Future 결과 wrapper
  72. 72 folly::Try vs Expected 선택 기준
  73. 73 folly::Range — 일반 iterator pair
  74. 74 folly::Uri — URL 파서
  75. 75 folly Fingerprint64·128 — 분산 hash
  76. 76 folly SpookyHashV2 — fast non-crypto hash
  77. 77 folly::Init — main() 부트스트랩
  78. 78 folly::Indestructible — global lifetime 패턴
  79. 79 folly::MicroLock — 1-byte 락
  80. 80 folly::MicroSpinLock — 가장 좁은 spin lock
  81. 81 folly::format — legacy formatter 분석
  82. 82 folly::demangle — typeid 디망글링
  83. 83 folly::DynamicConverter — dynamic ↔ struct
  84. 84 folly::RecordIO — append-only 로그 파일 포맷
  85. 85 folly::io::Compression — zstd·lz4·snappy wrapper
  86. 86 folly::AsyncIO — io_uring·Linux AIO
  87. 87 folly::CancellationToken — 코루틴·Future 취소 전파
  88. 88 folly::observer — hot config의 atomic refresh
  89. 89 fbcode 패턴 모음 — folly 사용의 실전