folly::Future retry·window·via — 제어 흐름 조합자
한 줄 요약:
retry는 실패 시 재시도,window는 동시성 제한,via는 executor 전환이다. 이 세 조합자가 Future 코드의 제어 흐름을 표현한다.
#동기 — 단순 체인을 넘는 제어
.thenValue와 collect만으로는 표현되지 않는 패턴이 있다.
- “실패하면 최대 3번 재시도하고, 매번 2배 backoff”
- “1000개 요청을 동시에 100개씩만 처리”
- “I/O 작업은 IO pool에서, 결과 처리는 다른 CPU pool에서”
이 패턴들은 retry/window/via 세 조합자로 표현된다.
#retry — 재시도 정책
#include <folly/futures/Retrying.h>
// 즉시 재시도, 최대 3회auto sf = folly::futures::retrying( folly::futures::retryingPolicyBasic(3), [](size_t attempt) { LOG(INFO) << "attempt " << attempt; return doRpc(); // SemiFuture<Response> });
// jittered exponential backoffauto sf2 = folly::futures::retrying( folly::futures::retryingPolicyCappedJitteredExponentialBackoff( 5, // 최대 5회 std::chrono::milliseconds(100), // base delay std::chrono::seconds(10), // max delay 0.1, // jitter ratio rng, [](size_t /*attempt*/, exception_wrapper const& ew) { // shouldRetry — 특정 예외만 재시도 return !ew.is_compatible_with<NonRetryableError>(); }), [](size_t attempt) { return doRpc(); });policy는 (attempt, exception_wrapper) -> SemiFuture<bool>로 재시도할지를 결정한다. true면 delay 후 다시 호출한다.
// folly/futures/Retrying.h (개념)template <class Policy, class FF>SemiFuture<R> retrying(Policy policy, FF func) { return func(0).thenTry([=, p = std::move(policy)](Try<R> t) -> SemiFuture<R> { if (t.hasValue()) return makeSemiFuture(*std::move(t)); return p(0, t.exception()).thenValue([](bool retry) { if (!retry) throw t.exception(); return retrying(p, func); // recursion }); });}내부는 recursive로 구현되지만 tail call로 펼쳐지므로 스택이 쌓이지 않는다(Future continuation은 heap에 살아 있음).
#자주 쓰는 policy
| Policy | 설명 |
|---|---|
retryingPolicyBasic(n) | 즉시 재시도 n회 |
retryingPolicyCappedJitteredExponentialBackoff | exponential + jitter |
retryingPolicyCappedExponentialBackoff | exponential 만 |
| 사용자 정의 | (attempt, ew) -> SemiFuture<bool> |
#window — 동시성 제한
#include <folly/futures/Future.h>
std::vector<std::string> urls = ...; // 10,000개
// 동시에 100개씩만auto sf = folly::window( std::move(urls), [](std::string url) -> SemiFuture<Response> { return fetchAsync(url); }, 100); // window size
// sf: SemiFuture<vector<Try<Response>>>sf.via(&pool).thenValue([](auto results) { process(results);});window는 cardinality와 메모리 폭발을 막는다. 10,000 RPC를 한 번에 띄우면 file descriptor가 부족하거나 다운스트림이 throttle한다. window=100이면 100개씩 진행하다 하나 끝날 때마다 다음 하나를 시작한다.
// folly/futures/Future-inl.h (개념)template <class Range, class F>SemiFuture<vector<Try<R>>> window(Range input, F func, size_t cap) { auto ctx = std::make_shared<WindowContext>(input.size()); for (size_t i = 0; i < cap && i < input.size(); ++i) { spawn(ctx, input, func, i); // 첫 cap개 시작 } return ctx->promise.getSemiFuture();}
void spawn(ctx, input, func, idx) { func(input[idx]).setCallback_([=](Try<R> t) { ctx->results[idx] = std::move(t); size_t next = ctx->nextIdx.fetch_add(1); if (next < input.size()) spawn(ctx, input, func, next); if (ctx->remaining.fetch_sub(1) == 1) ctx->promise.setValue(...); });}#via — executor 전환
folly::IOThreadPoolExecutor io(2);folly::CPUThreadPoolExecutor cpu(8);
fetchAsync(url) .via(&cpu) // 받은 body를 CPU pool에서 parse .thenValue(parse) .via(&io) // 결과를 IO pool에서 write .thenValue(writeFile) .get();.via(executor)는 그 이후 continuation이 도는 executor를 바꾼다. I/O와 CPU 작업을 다른 thread pool에 분리할 때 핵심이다.
SemiFuture<T>::via(Executor*)는 SemiFuture를 Future로 바인딩하지만, Future<T>::via(Executor*)는 재바인딩한다.
template <class T>Future<T> Future<T>::via(Executor::KeepAlive<> e) && { auto sf = std::move(*this).semi(); // 먼저 SemiFuture로 return std::move(sf).via(std::move(e));}#within — timeout
fetchAsync(url) .within(std::chrono::seconds(5)) // 5초 안에 안 끝나면 timeout .thenError(folly::tag_t<folly::FutureTimeout>{}, [](auto&) { return Response::timeout(); });내부적으로 timer thread를 사용해 지정 시간 후 cancellation을 트리거한다. 원래 작업은 계속 돌 수도 있지만 결과는 무시된다.
onTimeout은 비슷하지만 기본값을 직접 반환하는 변형이다.
fetchAsync(url).onTimeout(std::chrono::seconds(5), [] { return Response::cached();});#조합 예 — retry + window + via
// 1000개 URL을 동시 50개씩, 각각 최대 3회 재시도, CPU pool에서 처리
folly::window( std::move(urls), [](std::string url) { return folly::futures::retrying( folly::futures::retryingPolicyBasic(3), [url](size_t) { return fetchAsync(url); }); }, 50) .via(&cpu) .thenValue([](std::vector<Try<Response>> results) { size_t ok = 0; for (auto& r : results) if (r.hasValue()) ++ok; LOG(INFO) << "ok=" << ok; });선언적 표현으로 동시성 + 재시도 + executor가 모두 한 화면에 들어온다.
#std/Abseil과 비교
표준에는 없다. Abseil도 없다. Folly의 retry/window/via는 고유한 영역이다.
C++26 senders/receivers (P2300) 에서는 let_value/bulk/schedule 조합으로 표현된다.
Folly std::execution───────────────── ─────────────────.via(e) on(scheduler, sender)window(range, f, n) bulk(range, f) + schedulerretry(policy, f) let_error(sender, retry_logic)within(d) stop_when(sender, timer(d))#코드 리뷰 포인트
- retry policy가 모든 예외에 적용되는가? non-retryable error를 분류하지 않으면 무한 재시도 위험.
- window cap이 합리적인가? 다운스트림 capacity와 일치하는지 확인.
- via 후 다음 thenValue가 어느 executor에서 도는지 명확한가? 마지막
.via가 우세하다. - within 후 timeout 처리가 있는가?
.thenError<FutureTimeout>또는.onTimeout사용.
#자주 보는 안티패턴
// 1. retry policy 없음 — 무한 재시도folly::futures::retrying([](size_t) { return doRpc(); }); // 컴파일 OK지만 위험
// 2. window cap이 너무 큼folly::window(million_urls, fetch, 1'000'000); // window 의미 없음 — collect와 동일
// 3. via를 한 번도 안 부르고 thenValue 체인computeSemi().deferValue(...).deferValue(...).get();// 내부적으로 InlineExecutor — caller thread에서 dom
// 4. within timeout이 실제 작업보다 짧음 (의도된 게 아니라면)fetchAsync(slowUrl).within(std::chrono::milliseconds(1)).get();// 거의 항상 timeout#정리
retry는 정책에 따라 실패 재시도,window는 동시성 cap,via는 executor 전환이다.within/onTimeout은 작업에 시한을 건다.- retry policy는 재시도 여부를 동적으로 결정한다. non-retryable error 분류 필수.
- 세 조합자는 선언적으로 결합되어 복잡한 워크플로를 한 화면에 표현한다.
- C++26 senders/receivers에서
bulk/let_error/stop_when으로 대응된다.
#다음 편
coroutine)에서 stackful coroutine 모델을 본다.#관련 항목
Folly Code Review · 12 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::CancellationToken — 코루틴·Future 취소 전파
CancellationSource/Token의 전파 모델 — coroutine·Future·callback 트리에서 협력적 취소.
같은 시리즈에서 이어 읽기
folly::Try — Future 결과 wrapper
Try<T>의 세 상태 (value/exception/empty), Future 내부에서의 역할, exception_wrapper와의 관계.
같은 시리즈에서 이어 읽기
folly::collect·collectAll·collectAny — fan-in 패턴 분석
여러 SemiFuture를 모으는 세 가지 의미 — 모두 성공, 모두 완료, 하나만 완료.
같은 시리즈에서 이어 읽기