SlideShare a Scribd company logo
1 of 35
Download to read offline
아주 심플한 블룸필터의 원리
강대명 (CHARSYAM@NAVER.COM)
블룸필터가 뭔가요?
있다고 하면 없을 수 있지만(False Positive), 없다고
하면 정말 없는 자료구조(No False Negative)
실화입니까?
있다고 해도 실제로 없을 수 있다면, 매번 있는지 확인해
야 할 것 같은데, 이런 걸 어디에 써야 하나요?
HashMap 등은 contains에 있으면 반드시 있으니, 믿
고 쓸 수 있는데 말입니다.
블룸필터를 쓰고 있는 것들?
Cassandra
Hbase
Oracle(Bloom pruning of partitions for queries)
Quora, FaceBook
실화입니까?(2)
이런 제품들이나 회사들이 블룸필터를 쓰는 이유는 무엇
일까요?
DISK와 메모리의 속도비교
 L1 cache reference 0.5 ns
 Branch mispredict 5 ns
 L2 cache reference 7 ns 14x L1 cache
 Mutex lock/unlock 25 ns
 Main memory reference 100 ns 20x L2 cache, 200x L1 cache
 Compress 1K bytes with Zippy 3,000 ns 3 us
 Send 1K bytes over 1 Gbps network 10,000 ns 10 us
 Read 4K randomly from SSD* 150,000 ns 150 us ~1GB/sec SSD
 Read 1 MB sequentially from memory 250,000 ns 250 us
 Round trip within same datacenter 500,000 ns 500 us
 Read 1 MB sequentially from SSD* 1,000,000 ns 1,000 us 1 ms ~1GB/sec SSD, 4X
memory
 Disk seek 10,000,000 ns 10,000 us 10 ms 20x datacenter roundtrip
 Read 1 MB sequentially from disk 20,000,000 ns 20,000 us 20 ms 80x memory, 20X
SSD
 Send packet CA->Netherlands->CA 150,000,000 ns 150,000 us 150 ms
메인메모리와 디스크
디스크 접근은 메모리보다 겨우 10,000배 느립니다.
MEM 속도 = 디스크 * 10,000
SSD는 1,500 배 느림.
MEM 속도 = SSD * 1,500
결론 디스크 접근을 줄이자.
블룸필터의 필요성
실제 데이터가 있는지 정확히 알려면?
메모리가 데이터 사이즈 만큼 필요함.
데이터량이 굉장히 많다면?
블룸필터를 이용하면 메모리 사용량을 줄이면서 비슷한 효과
를 낼 수 있음.
블룸필터의 필요성
블
룸
필
터
SSD/HDD
Query
Query
Query
Query
exist
exist
exist
not exist
Query
Query
not exist
not exist
exist
exist
not exist
실제 3번의 쿼리를 할 필요가 없음.
How 블룸필터 works?
블룸필터는 bitarray 입니다.
n개의 hash를 선택합니다.(crc, murmur, md5등)
보통 3개
hash(key, 0) 은 crc hash를 의미
hash(key, 1) 은 murmur hash를 의미
hash(key, 2) 은 md5 hash를 의미
블룸필터 #1
 bitarray의 크기는 16
 hash(“charsyam”, 0) % 16 = 3
 hash(“charsyam”, 1) % 16 = 5
 hash(“charsyam”, 2) % 16 = 11
0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0
add(“charsyam”)
블룸필터 #2
 bitarray의 크기는 16
 hash(“bloomfilter”, 0) % 16 = 0
 hash(“bloomfilter”, 1) % 16 = 1
 hash(“bloomfilter”, 2) % 16 = 15
1 1 0 1 0 1 0 0 0 0 0 1 0 0 0 1
add(“bloomfilter”)
블룸필터 #3
 bitarray의 크기는 16
 hash(“clark”, 0) % 16 = 1
 hash(“clark”, 1) % 16 = 2
 hash(“clark”, 2) % 16 = 14
1 1 1 1 0 1 0 0 0 0 0 1 0 0 1 1
add(“clark”)
블룸필터 #4
 exists 동작, 3개의 비트가 1로 채워져 있으면 존재한다고 알림.
 hash(“charsyam”, 0) % 16 = 3
 hash(“charsyam”, 1) % 16 = 5
 hash(“charsyam”, 2) % 16 = 11
1 1 1 1 0 1 0 0 0 0 0 1 0 0 1 1
exists(“charsyam”)
블룸필터 #5
 exists, False Positive, fake는 추가하지 않았지만 모든 bit가 1임
 hash(“fake”, 0) % 16 = 0
 hash(“fake”, 1) % 16 = 3
 hash(“fake”, 2) % 16 = 15
1 1 1 1 0 1 0 0 0 0 0 1 0 0 1 1
exists(“fake”)
블룸필터의 한계 #1
데이터의 삭제가 불가능하다.
Hbase, Cassandra
지워지는 케이스는 없고 Compaction시에 재생성
블룸필터의 한계 #2
false positive 가 발생하는 비율을 적절히 조절해야 한다.
False Positive #1
False Positive는 당연히 발생하게 됨.
k: 해시 함수 개수
m: bitarray의 크기
n: 전체 원소의 개수
당연히 m이 크고 n이 적을 수록 False Positive가 적음
그럼 k는?
False Positive #2
가장 적은 False Positive를 가지는 경우
False Positive #3
한번의 hash 연산으로 나온 Bit를 1로 설정
한번의 hash 연산으로 BitArray V의 어떤 값이 설정될
확률 = 1/m
반대로 어떤 값이 설정 안될 확률은 (1 – 1/m)
False Positive #4
k 개의 해시 함수를 이용할 경우에 설정되지 않을 확률은
n 개의 원소가 들어가게 되면 다시 이 확률은
False Positive #5
이제 다시 n개의 원소가 있을 때 특정 Bit가 1로 셋팅되어
있을 확률은 1 에서 해당 값을 빼면 됨.
False Positive #6
k 개의 해시 함수가 실행되는 것과 위의 1로 설정될 확률이
독립 사건이므로…(이 부분이 이해가 안가요!!! ㅋㅋㅋ)
각각의 해시 함수가 실행될 때 마다 이 확률이라서…
False Positive #7
 다시 m 이 무한으로 수렴한다고 하면 그 값이 아래와 같이 되므
로…
False Positive #8
즉 False Postivie가 발생할 확률은 아래의 식이 도출됨
(뭐지 이건 또 T.T)
False Positive #9
다시, 가장 적은 False Positive를 가지는 경우
False Positive #10
다시, 가장 적은 False Positive를 가지는 경우 k를 유지할
경우에 m, n의 변화에 따른 False Postivie 확률 p의 변화
Scalable BloomFilter #1
블룸필터를 확장 가능하게 만들 수 있을까?
 즉, 처음에 원소가 적을 때는 m을 작게 잡고, 윈소가 늘어나면
m을 크게 만들면 좋지 않을까?
0 0 0 1
최초
1 1 1 1 0 1 0 0
확장
Scalable BloomFilter #2
기존 블룸필터의 확장은 불가능
 배열의 크기가 커지면 해시에 대한 modular도 달라지면서 기
존 값들의 의미가 전부 사라짐. 그러면 새로 만들어야 함.
Scalable BloomFilter #3
 새로운 블룸필터를 만들어서, 함께 유지한다.
0 0 0 1 0 0 0 1 1 1 1 1
0 10
0 0 0 1 1 1 1 1
0 1
0 0 0 1 1 1 1 1
0 1
0 0 0 1
2
Scalable BloomFilter #4
 Add 동작
입력 key가 기존 블룸필터들에 존재하는 지 확인 있으면, 리턴!
없으면, 여유 공간이 있는지 보고, 새로운 블룸필터 체인을 만들
어야 하는지 확인
맨 마지막 블룸필터에 삽입한다.
Scalable BloomFilter #5
 check 동작
모든 블룸필터 체인에서 검색을 해서 없어야만 없다고 알려준다.
Scalable BloomFilter #6
 확장시에 새 블룸필터의 사이즈는 더 늘어날 수 있다.
이에 따라 에러율도 바뀌어야 한다.
ERROR_TIGHTENING_RATIO 라는 개념이 적용되는데, 이건 패스…
Reference
 꼭 참고하세요.
 https://en.wikipedia.org/wiki/Bloom_filter
 http://d2.naver.com/helloworld/749531
 http://gsd.di.uminho.pt/members/cbm/ps/dbloom.pdf
 https://github.com/RedisLabsModules/rebloom
 https://github.com/jaybaird/python-bloomfilter/
Thank you.

More Related Content

What's hot

CERN’s Next Generation Data Analysis Platform with Apache Spark with Enric Te...
CERN’s Next Generation Data Analysis Platform with Apache Spark with Enric Te...CERN’s Next Generation Data Analysis Platform with Apache Spark with Enric Te...
CERN’s Next Generation Data Analysis Platform with Apache Spark with Enric Te...Databricks
 
Rethinking State Management in Cloud-Native Streaming Systems
Rethinking State Management in Cloud-Native Streaming SystemsRethinking State Management in Cloud-Native Streaming Systems
Rethinking State Management in Cloud-Native Streaming SystemsYingjun Wu
 
MySQL GTID 시작하기
MySQL GTID 시작하기MySQL GTID 시작하기
MySQL GTID 시작하기I Goo Lee
 
Stephan Ewen - Experiences running Flink at Very Large Scale
Stephan Ewen -  Experiences running Flink at Very Large ScaleStephan Ewen -  Experiences running Flink at Very Large Scale
Stephan Ewen - Experiences running Flink at Very Large ScaleVerverica
 
Virtual Flink Forward 2020: Netflix Data Mesh: Composable Data Processing - J...
Virtual Flink Forward 2020: Netflix Data Mesh: Composable Data Processing - J...Virtual Flink Forward 2020: Netflix Data Mesh: Composable Data Processing - J...
Virtual Flink Forward 2020: Netflix Data Mesh: Composable Data Processing - J...Flink Forward
 
STKI IT Delivery staffing ratios 2018 v3
STKI IT Delivery staffing ratios 2018 v3STKI IT Delivery staffing ratios 2018 v3
STKI IT Delivery staffing ratios 2018 v3Pini Cohen
 
Understanding and tuning WiredTiger, the new high performance database engine...
Understanding and tuning WiredTiger, the new high performance database engine...Understanding and tuning WiredTiger, the new high performance database engine...
Understanding and tuning WiredTiger, the new high performance database engine...Ontico
 
Time-Series Apache HBase
Time-Series Apache HBaseTime-Series Apache HBase
Time-Series Apache HBaseHBaseCon
 
Internal Architecture of Amazon Aurora (Level 400) - 발표자: 정달영, APAC RDS Speci...
Internal Architecture of Amazon Aurora (Level 400) - 발표자: 정달영, APAC RDS Speci...Internal Architecture of Amazon Aurora (Level 400) - 발표자: 정달영, APAC RDS Speci...
Internal Architecture of Amazon Aurora (Level 400) - 발표자: 정달영, APAC RDS Speci...Amazon Web Services Korea
 
관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016
관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016
관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016Amazon Web Services Korea
 
A Technical Introduction to WiredTiger
A Technical Introduction to WiredTigerA Technical Introduction to WiredTiger
A Technical Introduction to WiredTigerMongoDB
 
Amazon DocumentDB - Architecture 및 Best Practice (Level 200) - 발표자: 장동훈, Sr. ...
Amazon DocumentDB - Architecture 및 Best Practice (Level 200) - 발표자: 장동훈, Sr. ...Amazon DocumentDB - Architecture 및 Best Practice (Level 200) - 발표자: 장동훈, Sr. ...
Amazon DocumentDB - Architecture 및 Best Practice (Level 200) - 발표자: 장동훈, Sr. ...Amazon Web Services Korea
 
MongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To TransactionsMongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To TransactionsMydbops
 
Introduction to Kafka Cruise Control
Introduction to Kafka Cruise ControlIntroduction to Kafka Cruise Control
Introduction to Kafka Cruise ControlJiangjie Qin
 
Building Data Product Based on Apache Spark at Airbnb with Jingwei Lu and Liy...
Building Data Product Based on Apache Spark at Airbnb with Jingwei Lu and Liy...Building Data Product Based on Apache Spark at Airbnb with Jingwei Lu and Liy...
Building Data Product Based on Apache Spark at Airbnb with Jingwei Lu and Liy...Databricks
 
RocksDB detail
RocksDB detailRocksDB detail
RocksDB detailMIJIN AN
 
Big Data Architectural Patterns and Best Practices on AWS
Big Data Architectural Patterns and Best Practices on AWSBig Data Architectural Patterns and Best Practices on AWS
Big Data Architectural Patterns and Best Practices on AWSAmazon Web Services
 
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교Amazon Web Services Korea
 

What's hot (20)

CERN’s Next Generation Data Analysis Platform with Apache Spark with Enric Te...
CERN’s Next Generation Data Analysis Platform with Apache Spark with Enric Te...CERN’s Next Generation Data Analysis Platform with Apache Spark with Enric Te...
CERN’s Next Generation Data Analysis Platform with Apache Spark with Enric Te...
 
Rethinking State Management in Cloud-Native Streaming Systems
Rethinking State Management in Cloud-Native Streaming SystemsRethinking State Management in Cloud-Native Streaming Systems
Rethinking State Management in Cloud-Native Streaming Systems
 
MySQL GTID 시작하기
MySQL GTID 시작하기MySQL GTID 시작하기
MySQL GTID 시작하기
 
Stephan Ewen - Experiences running Flink at Very Large Scale
Stephan Ewen -  Experiences running Flink at Very Large ScaleStephan Ewen -  Experiences running Flink at Very Large Scale
Stephan Ewen - Experiences running Flink at Very Large Scale
 
Deep Dive on Amazon Aurora
Deep Dive on Amazon AuroraDeep Dive on Amazon Aurora
Deep Dive on Amazon Aurora
 
Virtual Flink Forward 2020: Netflix Data Mesh: Composable Data Processing - J...
Virtual Flink Forward 2020: Netflix Data Mesh: Composable Data Processing - J...Virtual Flink Forward 2020: Netflix Data Mesh: Composable Data Processing - J...
Virtual Flink Forward 2020: Netflix Data Mesh: Composable Data Processing - J...
 
STKI IT Delivery staffing ratios 2018 v3
STKI IT Delivery staffing ratios 2018 v3STKI IT Delivery staffing ratios 2018 v3
STKI IT Delivery staffing ratios 2018 v3
 
Understanding and tuning WiredTiger, the new high performance database engine...
Understanding and tuning WiredTiger, the new high performance database engine...Understanding and tuning WiredTiger, the new high performance database engine...
Understanding and tuning WiredTiger, the new high performance database engine...
 
Time-Series Apache HBase
Time-Series Apache HBaseTime-Series Apache HBase
Time-Series Apache HBase
 
Internal Architecture of Amazon Aurora (Level 400) - 발표자: 정달영, APAC RDS Speci...
Internal Architecture of Amazon Aurora (Level 400) - 발표자: 정달영, APAC RDS Speci...Internal Architecture of Amazon Aurora (Level 400) - 발표자: 정달영, APAC RDS Speci...
Internal Architecture of Amazon Aurora (Level 400) - 발표자: 정달영, APAC RDS Speci...
 
관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016
관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016
관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016
 
A Technical Introduction to WiredTiger
A Technical Introduction to WiredTigerA Technical Introduction to WiredTiger
A Technical Introduction to WiredTiger
 
Amazon DocumentDB - Architecture 및 Best Practice (Level 200) - 발표자: 장동훈, Sr. ...
Amazon DocumentDB - Architecture 및 Best Practice (Level 200) - 발표자: 장동훈, Sr. ...Amazon DocumentDB - Architecture 및 Best Practice (Level 200) - 발표자: 장동훈, Sr. ...
Amazon DocumentDB - Architecture 및 Best Practice (Level 200) - 발표자: 장동훈, Sr. ...
 
MongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To TransactionsMongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To Transactions
 
Introduction to Kafka Cruise Control
Introduction to Kafka Cruise ControlIntroduction to Kafka Cruise Control
Introduction to Kafka Cruise Control
 
Building Data Product Based on Apache Spark at Airbnb with Jingwei Lu and Liy...
Building Data Product Based on Apache Spark at Airbnb with Jingwei Lu and Liy...Building Data Product Based on Apache Spark at Airbnb with Jingwei Lu and Liy...
Building Data Product Based on Apache Spark at Airbnb with Jingwei Lu and Liy...
 
Deep Dive on Amazon S3
Deep Dive on Amazon S3Deep Dive on Amazon S3
Deep Dive on Amazon S3
 
RocksDB detail
RocksDB detailRocksDB detail
RocksDB detail
 
Big Data Architectural Patterns and Best Practices on AWS
Big Data Architectural Patterns and Best Practices on AWSBig Data Architectural Patterns and Best Practices on AWS
Big Data Architectural Patterns and Best Practices on AWS
 
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
 

Similar to Bloomfilter

[261] 실시간 추천엔진 머신한대에 구겨넣기
[261] 실시간 추천엔진 머신한대에 구겨넣기[261] 실시간 추천엔진 머신한대에 구겨넣기
[261] 실시간 추천엔진 머신한대에 구겨넣기NAVER D2
 
Webservice cache strategy
Webservice cache strategyWebservice cache strategy
Webservice cache strategyDaeMyung Kang
 
Memory corruption stack
Memory corruption stackMemory corruption stack
Memory corruption stackcodevania
 
B1 최신분산시스템이해결하고있는오래된이슈들
B1 최신분산시스템이해결하고있는오래된이슈들B1 최신분산시스템이해결하고있는오래된이슈들
B1 최신분산시스템이해결하고있는오래된이슈들NAVER D2
 
NDC 2018 억! 소리나는 게임 서비스 플랫폼을 지탱하는 알고리즘 - 해시, 불변데이터, 확률적 자료구조
NDC 2018 억! 소리나는 게임 서비스 플랫폼을 지탱하는 알고리즘 - 해시, 불변데이터, 확률적 자료구조NDC 2018 억! 소리나는 게임 서비스 플랫폼을 지탱하는 알고리즘 - 해시, 불변데이터, 확률적 자료구조
NDC 2018 억! 소리나는 게임 서비스 플랫폼을 지탱하는 알고리즘 - 해시, 불변데이터, 확률적 자료구조Isaac Jeon
 
[14.10.21] Far Cry and DX9 번역(shaderstudy)
[14.10.21] Far Cry and DX9 번역(shaderstudy)[14.10.21] Far Cry and DX9 번역(shaderstudy)
[14.10.21] Far Cry and DX9 번역(shaderstudy)해강
 
Open domain dialogue Chatbot(잡담봇 삽질기)
Open domain dialogue Chatbot(잡담봇 삽질기)Open domain dialogue Chatbot(잡담봇 삽질기)
Open domain dialogue Chatbot(잡담봇 삽질기)NAVER Engineering
 
Fabric High-throughtput
Fabric High-throughtputFabric High-throughtput
Fabric High-throughtputKyungSeok Lee
 
파이썬을 활용한 챗봇 서비스 개발 3일차
파이썬을 활용한 챗봇 서비스 개발 3일차파이썬을 활용한 챗봇 서비스 개발 3일차
파이썬을 활용한 챗봇 서비스 개발 3일차Taekyung Han
 

Similar to Bloomfilter (9)

[261] 실시간 추천엔진 머신한대에 구겨넣기
[261] 실시간 추천엔진 머신한대에 구겨넣기[261] 실시간 추천엔진 머신한대에 구겨넣기
[261] 실시간 추천엔진 머신한대에 구겨넣기
 
Webservice cache strategy
Webservice cache strategyWebservice cache strategy
Webservice cache strategy
 
Memory corruption stack
Memory corruption stackMemory corruption stack
Memory corruption stack
 
B1 최신분산시스템이해결하고있는오래된이슈들
B1 최신분산시스템이해결하고있는오래된이슈들B1 최신분산시스템이해결하고있는오래된이슈들
B1 최신분산시스템이해결하고있는오래된이슈들
 
NDC 2018 억! 소리나는 게임 서비스 플랫폼을 지탱하는 알고리즘 - 해시, 불변데이터, 확률적 자료구조
NDC 2018 억! 소리나는 게임 서비스 플랫폼을 지탱하는 알고리즘 - 해시, 불변데이터, 확률적 자료구조NDC 2018 억! 소리나는 게임 서비스 플랫폼을 지탱하는 알고리즘 - 해시, 불변데이터, 확률적 자료구조
NDC 2018 억! 소리나는 게임 서비스 플랫폼을 지탱하는 알고리즘 - 해시, 불변데이터, 확률적 자료구조
 
[14.10.21] Far Cry and DX9 번역(shaderstudy)
[14.10.21] Far Cry and DX9 번역(shaderstudy)[14.10.21] Far Cry and DX9 번역(shaderstudy)
[14.10.21] Far Cry and DX9 번역(shaderstudy)
 
Open domain dialogue Chatbot(잡담봇 삽질기)
Open domain dialogue Chatbot(잡담봇 삽질기)Open domain dialogue Chatbot(잡담봇 삽질기)
Open domain dialogue Chatbot(잡담봇 삽질기)
 
Fabric High-throughtput
Fabric High-throughtputFabric High-throughtput
Fabric High-throughtput
 
파이썬을 활용한 챗봇 서비스 개발 3일차
파이썬을 활용한 챗봇 서비스 개발 3일차파이썬을 활용한 챗봇 서비스 개발 3일차
파이썬을 활용한 챗봇 서비스 개발 3일차
 

More from DaeMyung Kang

How to use redis well
How to use redis wellHow to use redis well
How to use redis wellDaeMyung Kang
 
The easiest consistent hashing
The easiest consistent hashingThe easiest consistent hashing
The easiest consistent hashingDaeMyung Kang
 
How to name a cache key
How to name a cache keyHow to name a cache key
How to name a cache keyDaeMyung Kang
 
Integration between Filebeat and logstash
Integration between Filebeat and logstash Integration between Filebeat and logstash
Integration between Filebeat and logstash DaeMyung Kang
 
How to build massive service for advance
How to build massive service for advanceHow to build massive service for advance
How to build massive service for advanceDaeMyung Kang
 
Massive service basic
Massive service basicMassive service basic
Massive service basicDaeMyung Kang
 
Data Engineering 101
Data Engineering 101Data Engineering 101
Data Engineering 101DaeMyung Kang
 
How To Become Better Engineer
How To Become Better EngineerHow To Become Better Engineer
How To Become Better EngineerDaeMyung Kang
 
Kafka timestamp offset_final
Kafka timestamp offset_finalKafka timestamp offset_final
Kafka timestamp offset_finalDaeMyung Kang
 
Kafka timestamp offset
Kafka timestamp offsetKafka timestamp offset
Kafka timestamp offsetDaeMyung Kang
 
Data pipeline and data lake
Data pipeline and data lakeData pipeline and data lake
Data pipeline and data lakeDaeMyung Kang
 
webservice scaling for newbie
webservice scaling for newbiewebservice scaling for newbie
webservice scaling for newbieDaeMyung Kang
 

More from DaeMyung Kang (20)

Count min sketch
Count min sketchCount min sketch
Count min sketch
 
Redis
RedisRedis
Redis
 
Ansible
AnsibleAnsible
Ansible
 
Why GUID is needed
Why GUID is neededWhy GUID is needed
Why GUID is needed
 
How to use redis well
How to use redis wellHow to use redis well
How to use redis well
 
The easiest consistent hashing
The easiest consistent hashingThe easiest consistent hashing
The easiest consistent hashing
 
How to name a cache key
How to name a cache keyHow to name a cache key
How to name a cache key
 
Integration between Filebeat and logstash
Integration between Filebeat and logstash Integration between Filebeat and logstash
Integration between Filebeat and logstash
 
How to build massive service for advance
How to build massive service for advanceHow to build massive service for advance
How to build massive service for advance
 
Massive service basic
Massive service basicMassive service basic
Massive service basic
 
Data Engineering 101
Data Engineering 101Data Engineering 101
Data Engineering 101
 
How To Become Better Engineer
How To Become Better EngineerHow To Become Better Engineer
How To Become Better Engineer
 
Kafka timestamp offset_final
Kafka timestamp offset_finalKafka timestamp offset_final
Kafka timestamp offset_final
 
Kafka timestamp offset
Kafka timestamp offsetKafka timestamp offset
Kafka timestamp offset
 
Data pipeline and data lake
Data pipeline and data lakeData pipeline and data lake
Data pipeline and data lake
 
Redis acl
Redis aclRedis acl
Redis acl
 
Coffee store
Coffee storeCoffee store
Coffee store
 
Scalable webservice
Scalable webserviceScalable webservice
Scalable webservice
 
Number system
Number systemNumber system
Number system
 
webservice scaling for newbie
webservice scaling for newbiewebservice scaling for newbie
webservice scaling for newbie
 

Bloomfilter

  • 1. 아주 심플한 블룸필터의 원리 강대명 (CHARSYAM@NAVER.COM)
  • 2. 블룸필터가 뭔가요? 있다고 하면 없을 수 있지만(False Positive), 없다고 하면 정말 없는 자료구조(No False Negative)
  • 3. 실화입니까? 있다고 해도 실제로 없을 수 있다면, 매번 있는지 확인해 야 할 것 같은데, 이런 걸 어디에 써야 하나요? HashMap 등은 contains에 있으면 반드시 있으니, 믿 고 쓸 수 있는데 말입니다.
  • 4. 블룸필터를 쓰고 있는 것들? Cassandra Hbase Oracle(Bloom pruning of partitions for queries) Quora, FaceBook
  • 5. 실화입니까?(2) 이런 제품들이나 회사들이 블룸필터를 쓰는 이유는 무엇 일까요?
  • 6. DISK와 메모리의 속도비교  L1 cache reference 0.5 ns  Branch mispredict 5 ns  L2 cache reference 7 ns 14x L1 cache  Mutex lock/unlock 25 ns  Main memory reference 100 ns 20x L2 cache, 200x L1 cache  Compress 1K bytes with Zippy 3,000 ns 3 us  Send 1K bytes over 1 Gbps network 10,000 ns 10 us  Read 4K randomly from SSD* 150,000 ns 150 us ~1GB/sec SSD  Read 1 MB sequentially from memory 250,000 ns 250 us  Round trip within same datacenter 500,000 ns 500 us  Read 1 MB sequentially from SSD* 1,000,000 ns 1,000 us 1 ms ~1GB/sec SSD, 4X memory  Disk seek 10,000,000 ns 10,000 us 10 ms 20x datacenter roundtrip  Read 1 MB sequentially from disk 20,000,000 ns 20,000 us 20 ms 80x memory, 20X SSD  Send packet CA->Netherlands->CA 150,000,000 ns 150,000 us 150 ms
  • 7. 메인메모리와 디스크 디스크 접근은 메모리보다 겨우 10,000배 느립니다. MEM 속도 = 디스크 * 10,000 SSD는 1,500 배 느림. MEM 속도 = SSD * 1,500 결론 디스크 접근을 줄이자.
  • 8. 블룸필터의 필요성 실제 데이터가 있는지 정확히 알려면? 메모리가 데이터 사이즈 만큼 필요함. 데이터량이 굉장히 많다면? 블룸필터를 이용하면 메모리 사용량을 줄이면서 비슷한 효과 를 낼 수 있음.
  • 9. 블룸필터의 필요성 블 룸 필 터 SSD/HDD Query Query Query Query exist exist exist not exist Query Query not exist not exist exist exist not exist 실제 3번의 쿼리를 할 필요가 없음.
  • 10. How 블룸필터 works? 블룸필터는 bitarray 입니다. n개의 hash를 선택합니다.(crc, murmur, md5등) 보통 3개 hash(key, 0) 은 crc hash를 의미 hash(key, 1) 은 murmur hash를 의미 hash(key, 2) 은 md5 hash를 의미
  • 11. 블룸필터 #1  bitarray의 크기는 16  hash(“charsyam”, 0) % 16 = 3  hash(“charsyam”, 1) % 16 = 5  hash(“charsyam”, 2) % 16 = 11 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 add(“charsyam”)
  • 12. 블룸필터 #2  bitarray의 크기는 16  hash(“bloomfilter”, 0) % 16 = 0  hash(“bloomfilter”, 1) % 16 = 1  hash(“bloomfilter”, 2) % 16 = 15 1 1 0 1 0 1 0 0 0 0 0 1 0 0 0 1 add(“bloomfilter”)
  • 13. 블룸필터 #3  bitarray의 크기는 16  hash(“clark”, 0) % 16 = 1  hash(“clark”, 1) % 16 = 2  hash(“clark”, 2) % 16 = 14 1 1 1 1 0 1 0 0 0 0 0 1 0 0 1 1 add(“clark”)
  • 14. 블룸필터 #4  exists 동작, 3개의 비트가 1로 채워져 있으면 존재한다고 알림.  hash(“charsyam”, 0) % 16 = 3  hash(“charsyam”, 1) % 16 = 5  hash(“charsyam”, 2) % 16 = 11 1 1 1 1 0 1 0 0 0 0 0 1 0 0 1 1 exists(“charsyam”)
  • 15. 블룸필터 #5  exists, False Positive, fake는 추가하지 않았지만 모든 bit가 1임  hash(“fake”, 0) % 16 = 0  hash(“fake”, 1) % 16 = 3  hash(“fake”, 2) % 16 = 15 1 1 1 1 0 1 0 0 0 0 0 1 0 0 1 1 exists(“fake”)
  • 16. 블룸필터의 한계 #1 데이터의 삭제가 불가능하다. Hbase, Cassandra 지워지는 케이스는 없고 Compaction시에 재생성
  • 17. 블룸필터의 한계 #2 false positive 가 발생하는 비율을 적절히 조절해야 한다.
  • 18. False Positive #1 False Positive는 당연히 발생하게 됨. k: 해시 함수 개수 m: bitarray의 크기 n: 전체 원소의 개수 당연히 m이 크고 n이 적을 수록 False Positive가 적음 그럼 k는?
  • 19. False Positive #2 가장 적은 False Positive를 가지는 경우
  • 20. False Positive #3 한번의 hash 연산으로 나온 Bit를 1로 설정 한번의 hash 연산으로 BitArray V의 어떤 값이 설정될 확률 = 1/m 반대로 어떤 값이 설정 안될 확률은 (1 – 1/m)
  • 21. False Positive #4 k 개의 해시 함수를 이용할 경우에 설정되지 않을 확률은 n 개의 원소가 들어가게 되면 다시 이 확률은
  • 22. False Positive #5 이제 다시 n개의 원소가 있을 때 특정 Bit가 1로 셋팅되어 있을 확률은 1 에서 해당 값을 빼면 됨.
  • 23. False Positive #6 k 개의 해시 함수가 실행되는 것과 위의 1로 설정될 확률이 독립 사건이므로…(이 부분이 이해가 안가요!!! ㅋㅋㅋ) 각각의 해시 함수가 실행될 때 마다 이 확률이라서…
  • 24. False Positive #7  다시 m 이 무한으로 수렴한다고 하면 그 값이 아래와 같이 되므 로…
  • 25. False Positive #8 즉 False Postivie가 발생할 확률은 아래의 식이 도출됨 (뭐지 이건 또 T.T)
  • 26. False Positive #9 다시, 가장 적은 False Positive를 가지는 경우
  • 27. False Positive #10 다시, 가장 적은 False Positive를 가지는 경우 k를 유지할 경우에 m, n의 변화에 따른 False Postivie 확률 p의 변화
  • 28. Scalable BloomFilter #1 블룸필터를 확장 가능하게 만들 수 있을까?  즉, 처음에 원소가 적을 때는 m을 작게 잡고, 윈소가 늘어나면 m을 크게 만들면 좋지 않을까? 0 0 0 1 최초 1 1 1 1 0 1 0 0 확장
  • 29. Scalable BloomFilter #2 기존 블룸필터의 확장은 불가능  배열의 크기가 커지면 해시에 대한 modular도 달라지면서 기 존 값들의 의미가 전부 사라짐. 그러면 새로 만들어야 함.
  • 30. Scalable BloomFilter #3  새로운 블룸필터를 만들어서, 함께 유지한다. 0 0 0 1 0 0 0 1 1 1 1 1 0 10 0 0 0 1 1 1 1 1 0 1 0 0 0 1 1 1 1 1 0 1 0 0 0 1 2
  • 31. Scalable BloomFilter #4  Add 동작 입력 key가 기존 블룸필터들에 존재하는 지 확인 있으면, 리턴! 없으면, 여유 공간이 있는지 보고, 새로운 블룸필터 체인을 만들 어야 하는지 확인 맨 마지막 블룸필터에 삽입한다.
  • 32. Scalable BloomFilter #5  check 동작 모든 블룸필터 체인에서 검색을 해서 없어야만 없다고 알려준다.
  • 33. Scalable BloomFilter #6  확장시에 새 블룸필터의 사이즈는 더 늘어날 수 있다. 이에 따라 에러율도 바뀌어야 한다. ERROR_TIGHTENING_RATIO 라는 개념이 적용되는데, 이건 패스…
  • 34. Reference  꼭 참고하세요.  https://en.wikipedia.org/wiki/Bloom_filter  http://d2.naver.com/helloworld/749531  http://gsd.di.uminho.pt/members/cbm/ps/dbloom.pdf  https://github.com/RedisLabsModules/rebloom  https://github.com/jaybaird/python-bloomfilter/