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

folly::collect·collectAll·collectAny — fan-in 패턴 분석

· Hawk · 3분 읽기

한 줄 요약: collect모두 성공을, collectAll모두 완료(예외 포함)를, collectAny하나만 완료를 기다린다. 셋의 의미가 fan-in 패턴의 의도를 코드에 적는다.

#동기 — fan-in 패턴

비동기 시스템에서 자주 등장하는 구조는 여러 작업의 결과를 모으는 것이다.

Fan-in: collect / collectAll / collectAny

이를 일반화하면 세 가지 패턴이 보인다.

  1. all-or-nothing — 하나라도 실패하면 전체 실패 (예: parallel RPC가 모두 성공해야 응답)
  2. gather-all — 성공/실패를 모두 받아 부분 결과 활용 (예: 일부 서비스가 죽어도 응답)
  3. first-wins — 가장 먼저 완료된 하나만 사용 (예: redundant query, timeout race)

Folly는 이 셋을 collect/collectAll/collectAny로 명시한다.

#API 요약

#include <folly/futures/Future.h>
// (1) collect — 하나라도 실패하면 전체 실패
folly::SemiFuture<std::tuple<int, std::string>> sf1 =
folly::collect(makeSemiFuture(1), makeSemiFuture<std::string>("ok"));
folly::SemiFuture<std::vector<int>> sf2 =
folly::collect(vector_of_semifutures);
// (2) collectAll — 모두 완료 (Try로 감쌈)
folly::SemiFuture<std::tuple<Try<int>, Try<std::string>>> sf3 =
folly::collectAll(makeSemiFuture(1), makeSemiFuture<std::string>("ok"));
folly::SemiFuture<std::vector<Try<int>>> sf4 =
folly::collectAll(vector_of_semifutures);
// (3) collectAny — 가장 먼저 완료 (pair: index + Try)
folly::SemiFuture<std::pair<size_t, Try<int>>> sf5 =
folly::collectAny(vector_of_semifutures);
// (4) collectN — n개 완료
folly::SemiFuture<std::vector<std::pair<size_t, Try<int>>>> sf6 =
folly::collectN(vector_of_semifutures, 3);

#collect — 모두 성공해야 함

auto futures = std::vector{
fetchUser(1), // SemiFuture<User>
fetchUser(2),
fetchUser(3),
};
folly::collect(std::move(futures))
.via(&pool)
.thenValue([](std::vector<User> users) {
return aggregate(users);
})
.thenError(folly::tag_t<std::exception>{}, [](auto& e) {
LOG(ERROR) << "at least one fetch failed: " << e.what();
return Aggregate{};
});

하나라도 실패하면 첫 실패의 예외가 결과 SemiFuture로 전파된다. 나머지 작업은 계속 돌지만 결과는 버려진다.

// folly/futures/Future-inl.h (개념)
template <class It>
SemiFuture<std::vector<value_t>> collect(It first, It last) {
size_t n = std::distance(first, last);
auto ctx = std::make_shared<CollectContext>(n);
for (size_t i = 0; first != last; ++first, ++i) {
std::move(*first).setCallback_([ctx, i](Try<T>&& t) {
if (t.hasException()) {
ctx->setPartialResult(t.exception());
} else {
ctx->setPartialResult(i, *std::move(t));
}
});
}
return ctx->promise.getSemiFuture();
}

CollectContext남은 갯수를 atomic 카운터로 추적하고, 0이 되면 Promise를 set한다.

#collectAll — 부분 실패 허용

folly::collectAll(std::move(futures))
.via(&pool)
.thenValue([](std::vector<Try<User>> results) {
std::vector<User> ok;
size_t failed = 0;
for (auto& r : results) {
if (r.hasValue()) ok.push_back(*std::move(r));
else ++failed;
}
LOG(INFO) << "ok=" << ok.size() << " failed=" << failed;
return aggregate(ok);
});

각 결과가 Try<T>로 감싸져 예외도 값으로 다룬다. 부분 결과를 활용해야 할 때 적합하다.

#collectAny — race / first-wins

auto futures = std::vector{
queryReplicaA(),
queryReplicaB(),
queryReplicaC(),
};
folly::collectAny(std::move(futures))
.via(&pool)
.thenValue([](auto pair) {
auto [idx, result] = std::move(pair);
LOG(INFO) << "first replica: " << idx;
if (result.hasException()) {
// 가장 빠른 응답이 실패 — 다음 단계는 collectAnyWithoutException 고려
}
return *std::move(result);
});

가장 빠른 완료이지 가장 빠른 성공이 아니다. 가장 빠른 실패도 잡힌다. 성공만 원한다면 collectAnyWithoutException을 쓴다.

#collectAnyWithoutException — 모두 실패해야 실패

folly::collectAnyWithoutException(std::move(futures))
.via(&pool)
.thenValue([](auto pair) {
auto [idx, value] = std::move(pair); // 성공값
return value;
})
.thenError([](folly::exception_wrapper&&) {
return Default{}; // 모두 실패 — 마지막 예외
});

예외 없이 완료된 Future를 돌려준다. 하나도 성공하지 못하면 마지막 예외가 결과로 전달된다 (collectAny처럼 모든 예외를 모으지는 않는다).

#variadic vs range

collect 계열은 두 오버로드를 제공한다.

// variadic — 타입이 다른 Future
auto sf = folly::collect(
fetchUser(1), // SemiFuture<User>
fetchOrders(1), // SemiFuture<vector<Order>>
fetchAddress(1)); // SemiFuture<Address>
// sf: SemiFuture<tuple<User, vector<Order>, Address>>
// range — 같은 타입의 Future
std::vector<SemiFuture<User>> v = ...;
auto sf = folly::collect(std::move(v));
// sf: SemiFuture<vector<User>>

variadic은 서로 다른 type의 결과를 한 번에 모을 때 편리하다.

#collectN — n개 완료 기다림

auto sf = folly::collectN(std::move(futures), 3);
// sf: SemiFuture<vector<pair<size_t, Try<T>>>>
// 가장 빠른 3개를 받는다

quorum read 같은 패턴에 유용하다. 5개 replica 중 3개 응답을 받으면 진행한다.

#비교 표

API완료 시점결과 타입예외 처리
collect모두 성공 OR 첫 실패vector<T> 또는 tuple첫 예외 전파
collectAll모두 완료vector<Try<T>> 또는 tuple모두 Try로
collectAny첫 완료pair<size_t, Try<T>>Try로
collectAnySuccessful첫 성공 OR 모두 실패pair<size_t, T>모두 실패 시 예외
collectNn개 완료vector<pair<size_t, Try<T>>>Try로

#std와 비교

C++ 표준에는 fan-in primitive가 없다. std::async로 여러 작업을 띄우고 *각각 .get()*해야 한다.

// std로 동등 — sequential get
auto f1 = std::async(...);
auto f2 = std::async(...);
auto f3 = std::async(...);
auto r1 = f1.get(); // f2/f3는 끝나도 못 받음
auto r2 = f2.get();
auto r3 = f3.get();
// 첫 .get()이 blocking, 그 동안 다른 결과는 idle

folly::collect동시 wait을 한 번에 한다. context switch가 줄고, 가장 늦은 완료까지의 time만 든다.

#코드 리뷰 포인트

  • collect인지 collectAll인지 의도가 맞는가? 부분 실패 허용 여부가 결정한다.
  • 결과의 vector size가 input과 같은가? 그렇다. index 순서 유지된다.
  • collectAny의 결과가 실패면 다음 step이 처리하는가? 자주 빠뜨리는 부분.
  • 여러 작업이 서로 다른 executor에서 도는가? OK다. collect는 executor를 묶지 않는다.

#자주 보는 안티패턴

// 1. collect로 부분 실패 무시
folly::collect(futures).get();
// 하나만 실패해도 전체 throw — 의도가 partial이면 collectAll
// 2. collectAll 후 첫 예외만 체크
auto results = folly::collectAll(futures).get();
for (auto& r : results) {
if (r.hasException()) throw r.exception(); // 첫 예외만 본다
}
// 의도가 all-or-nothing이면 처음부터 collect 사용
// 3. collectAny가 실패해도 진행
folly::collectAny(futures).thenValue([](auto pair) {
return process(*pair.second); // pair.second가 예외면 throw
});
// 4. 무한히 큰 vector를 collect
folly::collect(million_futures); // memory 부담 — window로 분할

#정리

  • collect/collectAll/collectAny는 fan-in 패턴의 세 의미를 명시한다.
  • collect는 all-or-nothing, collectAll은 부분 실패 허용, collectAny는 first-wins다.
  • variadic 오버로드는 타입이 다른 Future를 tuple로, range 오버로드는 vector로 반환한다.
  • 결과는 input과 같은 index 순서를 유지한다.
  • collectN은 quorum 패턴에, collectAnySuccessful은 redundant query에 적합하다.
  • 큰 수의 작업에는 folly::window로 동시성 제한과 결합한다.

#다음 편

Part 2-06: retry / window / via에서 retry 정책, 동시성 제한, executor 전환을 본다.

#관련 항목

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