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

folly::observer — hot config의 atomic refresh

· Hawk · 4분 읽기

한 줄 요약: folly::observer드물게 업데이트되고 자주 읽히는 값을 atomic하게 refresh하는 framework다. config, feature flag, load balancer weight 같은 hot read 자리에서 lock 없이 새 값을 빌어온다.

#동기

production server에 동적으로 변하는 값이 많다.

  • feature flag (gating.enabled_for_user(uid)).
  • load balancer weight.
  • timeout threshold.
  • rate limit window.
  • experiment treatment.

이 값들은 수십만 req/sec에서 읽히고 수초~수분마다 한 번 갱신된다. naive 구현은 다음 함정이 있다.

std::mutex cfgMutex;
Config currentConfig;
Config GetConfig() {
std::lock_guard lk(cfgMutex); // 모든 read가 lock 경합
return currentConfig;
}

lock이 hot path에서 cache line ping-pong을 일으킨다.

std::atomic<std::shared_ptr<Config>> config; // C++20 atomic shared_ptr
Config GetConfig() {
return *config.load();
}

atomic shared_ptr가 표준이지만 모든 read마다 ref count CAS가 일어난다. 여전히 cache 비용.

folly::observerRCU 같은 방식으로 read를 lock-free, atomic-CAS-free에 가깝게 만든다.

#API

#include <folly/observer/Observer.h>
#include <folly/observer/SimpleObservable.h>
folly::observer::SimpleObservable<Config> obs{LoadInitialConfig()};
folly::observer::Observer<Config> read = obs.getObserver();
// 어딘가에서 update
obs.setValue(LoadNewConfig());
// hot path read
void HandleRequest() {
auto snapshot = read.getSnapshot();
// snapshot은 reference-stable Config*
if (snapshot->isFeatureEnabled()) {
// ...
}
}

두 타입.

  • SimpleObservable<T> — value를 들고 있는 owner. setValue로 갱신.
  • Observer<T> — read-only view. getSnapshot()이 hot path.

getSnapshot()은 거의 무료 (atomic load 1회 + thread-local cache).

#Snapshot 모델

folly::observer::Snapshot<Config> snap = obs.getSnapshot();
// snap이 살아있는 동안 T*가 안정 — refresh 일어나도 이 snapshot은 옛 값
const Config& cfg = *snap;
ProcessLong(cfg); // 중간에 setValue가 와도 cfg는 일관됨
// snapshot이 destroy되면 옛 값은 GC 가능

Snapshot<T>는 RAII로 reference를 잡는다. 잡고 있는 동안 그 버전의 T가 살아있다. 새 setValue가 와도 옛 snapshot 사용자는 영향 없음. snapshot이 모두 destroy되면 옛 버전이 GC.

이게 RCU(Read-Copy-Update)의 user-space 변형.

#합성 — observer chain

auto config = configObs.getObserver(); // Observer<Config>
auto timeoutObs = folly::observer::makeObserver([config] {
auto snap = (*config).getSnapshot();
return snap->timeout_ms; // 의존성 자동 추적
});
// 사용
void HandleReq() {
auto t = timeoutObs.getSnapshot();
ApplyTimeout(*t);
}

makeObserver([func])derived observer를 만든다. func 안에서 다른 observer를 snapshot하면 그것이 의존성으로 추적된다. 의존 observer가 update되면 derived도 자동 refresh.

선언적 dataflow — Excel formula 같은 모델.

#내부 구조

// folly/observer/Observer.h 약식
class ObserverCore {
public:
std::shared_ptr<const void> getCurrentValue() const;
void setValue(std::shared_ptr<const void> newVal);
// dependent observer
void addDependent(std::weak_ptr<ObserverCore> dep);
void notifyDependentsAsync(); // executor에 schedule
private:
std::atomic<std::shared_ptr<const void>> value_;
std::vector<std::weak_ptr<ObserverCore>> dependents_;
};
template <class T>
class Observer {
std::shared_ptr<ObserverCore> core_;
Snapshot<T> getSnapshot() const {
auto val = core_->getCurrentValue(); // atomic load + ref count
return Snapshot<T>{std::static_pointer_cast<const T>(val)};
}
};

값은 shared_ptr<const T>로 보관. setValue는 atomic store, getSnapshot은 atomic load + ref count. C++20 atomic shared_ptr 동작과 비슷하나 snapshot 자체가 thread-local 캐시될 수 있어 hot path가 빠르다.

#Thread-local snapshot 캐시

template <class T>
class TLObserver {
ThreadLocal<Snapshot<T>> cached_;
Observer<T> base_;
Snapshot<T> getSnapshot() {
auto& cache = *cached_;
if (cache && stillCurrent(cache)) return cache;
cache = base_.getSnapshot();
return cache;
}
};

TLObserver가 thread-local 캐시. 같은 thread에서 두 번째 read부터는 atomic load조차 회피.

#사용 패턴 — feature flag

class FeatureGate {
folly::observer::Observer<FlagSet> flags_;
public:
FeatureGate(folly::observer::Observer<FlagSet> obs) : flags_(std::move(obs)) {}
bool IsEnabled(folly::StringPiece name) const {
auto snap = flags_.getSnapshot();
return snap->contains(name);
}
};
// 어딘가에서 update
flagsObservable.setValue(LoadFromConfigServer());

config server에서 flag set이 update되면 다음 request부터 새 flag set 적용. 모든 read는 lock 없이 atomic load.

#std와의 비교

항목표준 (없음)folly::observerabsl (없음)std::atomic<shared_ptr>
자동 refreshN/Aderived observerN/A직접 update
dataflow chainN/AmakeObserverN/A없음
thread-local cacheN/ATLObserverN/A없음
snapshot lifetimeN/ARAII SnapshotN/Ashared_ptr
표준N/AfollyN/AC++20

C++20 std::atomic<std::shared_ptr<T>>원시 기능만 표준화. derived observer, thread-local cache 같은 고급 기능은 라이브러리.

#코드 리뷰 포인트

  • Observer를 매 request마다 새로 만듦 → ObserverCore 등록 비용. 한 번 생성해 멤버로 보관.
  • snapshot을 오래 잡고 있으면 옛 버전 GC 안 됨. 짧은 scope.
  • derived observer 안에서 비결정적 작업 (random, time)이 있으면 의존성 추적 깨짐. 순수 함수가 권장.
  • update가 매우 자주 (초당 수십 번)면 observer 모델이 부적합. atomic value 또는 다른 패턴.
  • TLObserver가 모든 자리에 필요한 건 아님 — extreme hot path만.

#자주 보는 안티패턴

// 1. snapshot을 멤버로 보관
struct Handler {
folly::observer::Snapshot<Config> snap_ = configObs.getSnapshot(); // 영원히 옛 값
void handle() { use(*snap_); } // refresh 안 됨
};
// → Observer를 보관하고 handle 안에서 getSnapshot
// 2. setValue를 hot path에서
void HandleReq(Req r) {
observable.setValue(newConfig); // request마다 update?
// → write가 자주면 observer 부적합
}
// 3. derived observer의 func 안에서 다른 thread 작업
auto derived = folly::observer::makeObserver([] {
return std::async([] { return load(); }); // 의존성 추적 안 됨
});
// 4. snapshot lifetime을 RAII 밖으로
const Config& cfg = *snap;
return &cfg; // snap이 scope 끝에 destroy → dangling

#실전 — load balancer weight

class LoadBalancer {
folly::observer::Observer<Weights> weights_;
public:
LoadBalancer(folly::observer::Observer<Weights> obs)
: weights_(std::move(obs)) {}
Backend& Pick() {
auto snap = weights_.getSnapshot();
return weightedRandom(*snap);
}
};
// background thread가 health check 기반 weight 계산
backgroundExecutor->add([&] {
auto newWeights = ComputeFromHealth();
weightsObservable.setValue(std::move(newWeights));
});

매 request의 Pick()은 lock-free atomic load. weight update는 background에서 분리. read/write가 각자의 hot path를 가진다.

#정리

  • folly::observer는 read-mostly 값의 atomic refresh framework.
  • SimpleObservable writer + Observer reader 분리.
  • Snapshot<T> RAII로 reference 안정성 보장.
  • makeObserver로 derived observer chain — Excel formula 같은 dataflow.
  • TLObserver로 thread-local cache, extreme hot path용.

#다음 편

Part 21-02: fbcode 패턴 모음으로 시리즈를 마무리한다.

#관련 항목

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