folly Fingerprint64·128 — 분산 hash
한 줄 요약:
Fingerprint64/128은 polynomial Rabin-Karp 기반 fixed-size hash다.std::hash가 in-process container용이라면 fingerprint는 서로 다른 프로세스/머신에서 같은 입력에 같은 결과를 보장해 sharding과 dedup의 키가 된다.
#동기
std::hash는 다음을 보장하지 않는다.
- 같은 입력에 같은 출력 (다른 컴파일러 / 다른 실행 사이).
- 분포가 좋다는 것.
- 충돌 attack 저항.
이것들이 in-process hash container에서는 큰 문제가 아니다. 같은 process가 끝나면 hash 결과는 무관. 그러나 다음 경우는 결정적이다.
- sharding —
hash(key) % N으로 어느 서버로 보낼지 결정. 모든 client가 같은 hash 함수를 써야. - content addressing — Git blob, IPFS CID. 같은 내용이면 같은 hash.
- dedup — log dedup, dataset dedup. 다른 머신에서 같은 hash.
이 자리에 std::hash는 부적합. Fingerprint64/128이 답이다.
#include <folly/Fingerprint.h>
folly::Fingerprint64 fp;fp.update(data, len);uint64_t h = fp.value();
// 또는 one-shotuint64_t h2 = folly::Fingerprint64{}.update(data, len).value();#알고리즘 — Rabin-Karp polynomial hash
입력: byte stream b[0], b[1], ..., b[n-1]다항식: H(x) = b[0]*x^(n-1) + b[1]*x^(n-2) + ... + b[n-1] mod P(x)
P(x) = 64-bit irreducible polynomial over GF(2) (Folly가 고른 specific polynomial)
연산: GF(2) 다항식 산술 (XOR + shift)핵심 특성:
- 분포 균등 — 좋은 polynomial에서 거의 균등.
- incremental computable —
update(chunk)반복 가능. - 다른 머신에서 같은 결과 — polynomial이 hardcoded.
// folly/Fingerprint.h 약식class Fingerprint64 { public: Fingerprint64& update(const uint8_t* data, size_t len) noexcept { for (size_t i = 0; i < len; ++i) { // GF(2)^64 다항식 mul + xor val_ = mulPoly(val_) ^ data[i]; } return *this; } uint64_t value() const noexcept { return val_; }
private: uint64_t val_ = 0;
static uint64_t mulPoly(uint64_t x) noexcept { // hardcoded irreducible polynomial과 GF(2) multiply // 보통 lookup table로 가속 return /* ... */; }};실제 구현은 8-byte chunk 단위 처리 + lookup table로 SWAR 가속. 그래도 SpookyHash나 xxhash보다 느리다. 결정적이고 sharding-safe하다는 게 가치.
#Fingerprint128 — 128-bit variant
folly::Fingerprint128 fp;fp.update(data, len);auto [hi, lo] = fp.value();// hi, lo: uint64_t 두 개64-bit가 충분치 않을 때 (예: 수억 객체 dedup, birthday paradox로 충돌 우려) 128-bit 사용. 두 개의 독립된 polynomial 결과를 (hi, lo)에 담는다.
birthday bound 계산:
64-bit : ~2^32 객체에서 50% 충돌 확률128-bit: ~2^64 객체에서 50% 충돌 확률수억 객체면 64-bit도 안전하지만 완전 안전이 필요하면 128.
#API 패턴
// streamingfolly::Fingerprint64 fp;fp.update(part1, len1);fp.update(part2, len2);auto h = fp.value();
// one-shot from StringPieceauto h2 = folly::Fingerprint64{} .update(reinterpret_cast<const uint8_t*>(s.data()), s.size()) .value();
// content-defined chunking 같은 곳에서 sliding window도 가능// (별도 RollingFingerprint 클래스 — Folly에는 없고 직접 구현)#std::hash 비교
struct Key { std::string s; };
// in-process containerstd::unordered_map<Key, V, std::hash<Key>> m; // OK
// shardingsize_t shard = std::hash<Key>{}(k) % N; // BAD — 다른 process에서 다른 결과 가능size_t shard = folly::Fingerprint64{}.update( reinterpret_cast<const uint8_t*>(k.s.data()), k.s.size()).value() % N; // OK| 항목 | std::hash | folly::Fingerprint64 | xxhash / WyHash | SpookyHash |
|---|---|---|---|---|
| 결정성 | 보장 안 함 | 보장 | 보장 (seed 고정) | 보장 |
| 분포 | 구현체 의존 | 좋음 | 매우 좋음 | 매우 좋음 |
| 속도 | 빠름 | 보통 | 매우 빠름 (SIMD) | 매우 빠름 |
| 64/128 | 64 | 64/128 | 64/128 | 64/128 |
| 사용처 | in-process | sharding/dedup | general fast | general fast |
| 표준 | C++ | folly | 외부 | 외부 |
xxhash나 WyHash가 더 빠르지만 folly 내부에서 sharding 키로는 Fingerprint가 역사적 표준. 새 코드라면 SpookyHashV2(다음 절) 또는 외부 xxhash도 검토.
#absl::Hash와의 비교
absl::Hash<T>는 in-process hash다. 같은 binary 안에서는 결정적이지만 binary 사이엔 다를 수 있다. std::hash의 더 일관된 버전.
absl::Hash<Key> h;size_t v = h(k);sharding에는 부적합 — fingerprint류가 옳다.
#코드 리뷰 포인트
- sharding 코드에
std::hash— 즉시Fingerprint64로 교체. - fingerprint를
unordered_map키로 — 의도가 고정 키가 아니면 over-engineering.std::hash가 빠르다. - 64-bit fingerprint로 수십억 객체 dedup — 128-bit 검토.
- 같은 데이터에 다른 alignment로 update — fingerprint는 byte stream 단위라 영향 없지만 byte order는 영향 있음. portable한 byte 순서로 input 만들어야.
#자주 보는 안티패턴
// 1. struct를 raw bytes로 fingerprintstruct K { int a; int b; };K k{1, 2};fp.update(reinterpret_cast<const uint8_t*>(&k), sizeof(K));// → padding/endianness/struct layout 의존 — 다른 머신에서 다른 결과
// 2. fingerprint를 cryptographic hash로 오해// → 의도적 충돌 만들 수 있음. Adversarial 입력엔 BLAKE3 / SHA-2.
// 3. fingerprint을 32-bit으로 잘라 shardingsize_t shard = (fp.value() & 0xFFFFFFFF) % N;// → lower bit의 분포가 떨어질 수 있음. fp 전체로 modulo.#실전 — log dedup
folly::F14FastSet<uint64_t> seenFingerprints;
void IngestLog(folly::StringPiece line) { auto fp = folly::Fingerprint64{} .update(reinterpret_cast<const uint8_t*>(line.data()), line.size()) .value(); if (!seenFingerprints.insert(fp).second) { return; // 중복 — drop } Persist(line);}같은 line이 들어오면 hash가 같아 중복 검출. 다른 서버가 같은 line을 emit해도 dedup 가능 — fingerprint가 결정적이라 가능한 패턴.
#정리
Fingerprint64/128은 다른 머신에서 같은 입력에 같은 결과를 보장하는 hash.- Rabin-Karp polynomial 기반, GF(2) 산술 + lookup table.
- sharding, content addressing, dedup 같은 자리에
std::hash가 아니라 fingerprint를 사용. - cryptographic 강도는 없음 — adversarial 입력에는 BLAKE3/SHA-2.
- 더 빠른 일반 hash가 필요하면 다음 절 SpookyHashV2 또는 외부 xxhash.
#다음 편
Part 17-04: SpookyHashV2에서 fast non-crypto hash를 본다.
#관련 항목
Folly Code Review · 75 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 SpookyHashV2 — fast non-crypto hash
SpookyHashV2의 ARX (Add/Rotate/Xor) 기반 빠른 hash — F14의 hasher 기본 후보.
같은 시리즈에서 이어 읽기
fbcode 패턴 모음 — folly 사용의 실전
Meta fbcode 코드 리뷰에서 반복적으로 등장하는 folly 사용 패턴 — overview + 시리즈 마무리.
같은 시리즈에서 이어 읽기
folly::observer — hot config의 atomic refresh
folly::observer — read mostly 값의 atomic refresh, hot config·feature flag·LB weight 같은 패턴의 표준.
같은 시리즈에서 이어 읽기