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

folly Meta 스타일 code review 패턴

· Hawk · 3분 읽기

#한 줄 요약

Meta의 코드 리뷰는 “Move Fast”의 이미지와 달리 라이브러리 코드에선 신중하다. Folly에 들어오는 PR은 벤치마크·메모리·스레드안전·예외안전 네 가지를 모두 증명해야 한다. 이 절에서는 그 lens를 통한 리뷰 체크리스트를 정리한다.

#Meta의 리뷰 철학

핵심 원칙은 한 줄로 표현된다.

Performance is a feature.

Folly에서 성능은 단순한 최적화 옵션이 아니다. throughput·latency 회귀가 발견되면 새 기능보다 우선해서 차단된다. PR마다 측정 가능한 결과를 요구한다.

Folly PR에서 필수로 따라붙는 항목.

  1. 벤치마크 결과 (전/후 비교)
  2. 메모리 사용량 분석
  3. 스레드 안전성 증명
  4. 예외 안전성 보장

#1. 성능 — 최우선 lens

#벤치마크 필수

새 함수·새 컨테이너·기존 핫패스 수정은 모두 folly/Benchmark.h 기반 측정이 따라온다.

BENCHMARK(fbstringCopy, iters) {
folly::fbstring s("benchmark string");
for (size_t i = 0; i < iters; ++i) {
folly::fbstring copy = s;
folly::doNotOptimizeAway(copy);
}
}
BENCHMARK(stdstringCopy, iters) {
std::string s("benchmark string");
for (size_t i = 0; i < iters; ++i) {
std::string copy = s;
folly::doNotOptimizeAway(copy);
}
}
// 결과 예시:
// fbstringCopy 100000000 12.3 ns
// stdstringCopy 100000000 45.6 ns → fbstring 3.7x 빠름

리뷰어가 묻는다.

  • 벤치마크 결과가 있는가?
  • 다양한 입력 크기에서 측정했는가?
  • 기존 구현 대비 개선되었는가?
  • p50/p99 분포는?

#메모리 할당 최소화

// 회피 — 매 push가 realloc 가능
std::string upper(const std::string& s) {
std::string r;
for (char c : s) r += std::toupper(c);
return r;
}
// Good — 미리 할당
std::string upper(const std::string& s) {
std::string r;
r.reserve(s.size());
for (char c : s) r += std::toupper(c);
return r;
}
// Better — in-place
void upperInPlace(std::string& s) {
for (char& c : s) c = std::toupper(c);
}

리뷰에서 “왜 alloc이 N번 일어나는가” 같은 질문이 흔하다.

#캐시 친화 설계

// 회피 — 흩어진 메모리
struct Node { Node* next; Node* prev; int data; };
std::list<Node> items;
// Good — 연속 메모리
std::vector<int> items;
// Folly 스타일
folly::fbvector<int> items; // jemalloc 통합

핫패스에선 cacheline 분석을 요구하기도 한다.

#2. 스레드 안전성

#명시적 문서화

/**
* Thread Safety:
* - All methods are thread-safe.
* - Multiple threads may call increment() concurrently.
*
* Memory Ordering:
* - Uses std::memory_order_relaxed for performance.
* - No happens-before relationship between operations.
*/
class Counter {
public:
void increment() noexcept { count_.fetch_add(1, std::memory_order_relaxed); }
int64_t get() const noexcept { return count_.load(std::memory_order_relaxed); }
private:
std::atomic<int64_t> count_{0};
};

memory order 선택 이유까지 명시. 단순 relaxed를 썼다면 그 이유와 안전성 분석이 필요.

#동기화 검증

// 회피 — 데이터 레이스
class Cache {
public:
void set(string k, int v) { data_[k] = v; } // unsynchronized
int get(string k) { return data_[k]; }
private:
std::unordered_map<string, int> data_;
};
// Good — 명시 동기화
class Cache {
public:
void set(string k, int v) {
std::lock_guard l(m_);
data_[k] = v;
}
std::optional<int> get(string k) {
std::lock_guard l(m_);
auto it = data_.find(k);
return it != data_.end() ? std::optional(it->second) : std::nullopt;
}
private:
std::mutex m_;
std::unordered_map<string, int> data_;
};
// Better — lock-free
class Cache {
public:
void set(string k, int v) { data_.insert_or_assign(k, v); }
std::optional<int> get(string k) {
auto it = data_.find(k);
return it != data_.end() ? std::optional(it->second) : std::nullopt;
}
private:
folly::ConcurrentHashMap<string, int> data_;
};

mutex가 답일 때도, ConcurrentHashMap이 답일 때도 있다. 리뷰어는 선택 이유를 묻는다.

#3. 예외 안전성

Folly는 예외를 적극 사용한다. 그래서 예외 안전성이 더 중요하다.

수준.

  • No-throw — 절대 발생 안 함 (noexcept).
  • Strong — 발생 시 상태 변경 없음.
  • Basic — 발생 시 유효한 상태 유지.
  • None — 보장 없음.

#Strong guarantee 예

// Good — 검증 먼저, 그 다음 commit
void transfer(Account& to, int amount) {
if (amount > balance_) throw std::runtime_error("insufficient");
balance_ -= amount;
try {
to.balance_ += amount;
} catch (...) {
balance_ += amount; // rollback
throw;
}
}
// Better — copy-and-commit
void transfer(Account& to, int amount) {
int new_balance = balance_ - amount;
int new_to = to.balance_ + amount;
if (new_balance < 0) throw std::runtime_error("insufficient");
// 검증 끝, 이제 noexcept commit
balance_ = new_balance;
to.balance_ = new_to;
}

#noexcept 올바른 사용

class Resource {
public:
// move는 noexcept이어야 STL container가 최적화
Resource(Resource&& o) noexcept : data_(std::exchange(o.data_, nullptr)) {}
Resource& operator=(Resource&& o) noexcept {
delete data_;
data_ = std::exchange(o.data_, nullptr);
return *this;
}
// 소멸자는 항상 noexcept
~Resource() noexcept { delete data_; }
private:
int* data_ = nullptr;
};

#4. API 설계

#일관성

// Good — STL 호환
class Container {
public:
size_t size() const;
bool empty() const;
void clear();
void reserve(size_t);
};
// 회피 — Java-style 혼재
class Container {
public:
size_t getSize() const;
bool isEmpty() const;
void Clear();
};

#0비용 추상화

template <typename T>
class Optional {
public:
template <typename F>
auto map(F&& f) const -> Optional<decltype(f(std::declval<T>()))> {
if (hasValue_) return Optional(f(value_));
return Optional();
}
};
// 사용: inline되어 런타임 오버헤드 없음
auto y = maybeInt.map([](int x){ return x * 2; });

#5. 테스트

#성능 회귀 테스트

TEST(StringPerf, CopyPerformance) {
folly::BenchmarkSuspender s;
folly::fbstring str(1000, 'x');
s.dismiss();
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 100000; ++i) {
folly::fbstring copy = str;
folly::doNotOptimizeAway(copy);
}
auto end = std::chrono::high_resolution_clock::now();
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() / 100000;
EXPECT_LT(ns, 50); // 회귀 가드
}

#스트레스 테스트

TEST(ConcurrentHashMapTest, ConcurrentAccess) {
folly::ConcurrentHashMap<int, int> map;
std::atomic<int> errors{0};
std::vector<std::thread> ts;
for (int i = 0; i < 10; ++i) {
ts.emplace_back([&, i]{
for (int j = 0; j < 10000; ++j) {
int k = i * 10000 + j;
map.insert(k, j);
auto it = map.find(k);
if (it == map.end() || it->second != j) ++errors;
}
});
}
for (auto& t : ts) t.join();
EXPECT_EQ(0, errors.load());
}

#리뷰어 질문 템플릿

#성능

필수:

  1. 벤치마크 결과 (전/후, 입력 크기별)
  2. 메모리 할당 패턴
  3. 핫패스 영향
  4. 캐시 미스 예상치

권장:

  1. SIMD 가능성
  2. branch prediction 친화성
  3. false sharing 가능성

#PR 본문 템플릿

## Summary
변경 내용
## Motivation
왜 필요한가
## Performance
### Benchmarks
Before:
op X: 100ns (p50), 150ns (p99)
After:
op X: 50ns (p50), 80ns (p99)
Improvement: 2x p50, 1.9x p99
### Memory
peak heap 변화
## Thread Safety
분석
## Test Plan
- [ ] unit
- [ ] benchmark
- [ ] stress
- [ ] ASAN/TSAN clean

#Folly 특유 리뷰 포인트

#Expected vs 예외

// Expected — 예상 가능한 실패
folly::Expected<User, Error> findUser(int id) {
if (!exists(id)) return folly::makeUnexpected(Error::NotFound);
return users_[id];
}
// 예외 — 프로그래머 오류 또는 복구 불가
void processUser(User* u) {
if (!u) throw std::invalid_argument("null");
}

#Future 체이닝 평탄화

// 회피 — 콜백 지옥
getUser(id).thenValue([](User u) {
return getOrders(u.id).thenValue([u](Orders o) {
return getPayments(o.id).thenValue([u,o](Payments p) {
return process(u, o, p);
});
});
});
// Good — collectAll
folly::collectAll(getUser(id), getOrders(orderId), getPayments(pid))
.thenValue([](auto t) {
auto [u, o, p] = t;
return process(u, o, p);
});

#코드 스타일

Folly는 Google C++ Style을 따르되 몇 가지 차이.

// 1. 예외 사용 OK
try { risky(); } catch (const std::exception& e) { handle(e); }
// 2. 매크로 사용 (FOLLY_*)
FOLLY_ALWAYS_INLINE void hotPath() {}
// 3. pImpl로 ABI 안정
class Impl;
// 4. 헤더 구조
// folly/Feature.h — 공개 API
// folly/detail/FeatureDetail.h — 구현 상세

#정리

  • Meta의 Folly 리뷰는 performance-first.
  • 모든 PR이 벤치마크·메모리·스레드·예외 안전을 증명.
  • 스레드 안전성은 memory order 선택 이유까지 문서화.
  • noexcept 보장으로 STL 컨테이너 최적화 활성.
  • API는 STL과 일관성 유지.
  • Future 체이닝은 collectAll로 평탄화 권장.

#다음 편

Part 14-02 Folly anti-patterns — 잘못 쓰면 std보다 느려지는 사례들.

#관련 항목

Folly Code Review · 62 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 사용의 실전