Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In
Continue with Google
Continue with Facebook
or use


Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here
Continue with Google
Continue with Facebook
or use


Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Have an account? Sign In Now

Sorry, you do not have a permission to ask a question, You must login to ask question.

Continue with Google
Continue with Facebook
or use


Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Stack Ask

Stack Ask Logo Stack Ask Logo

Stack Ask Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 6546
Next
In Process
Tuấn Vũ Đặng
  • 1
Tuấn Vũ ĐặngBeginner
Asked: July 27, 20222022-07-27T11:34:34+00:00 2022-07-27T11:34:34+00:00In: Programming

Hỏi về bài post Reddit count views

  • 1

Hi a Dũng, e có đọc qua blog của Reddit (https://www.redditinc.com/blog/view-counting-at-reddit), họ có nói là sử dụng Redis hyperloglog để count. Em muốn hỏi là tại sao họ k dùng redis incr để count, nếu mà dùng thì sẽ như thế nào. Vì redis là single thread nên nó sẽ tránh được race condition.

Em muốn hỏi thêm là bth những hệ thống count như này (stackaks) thì sẽ implement bằng cách nào ạ, chủ yếu là scale và tránh race condition.

Em cảm ơn ạ.

hyperloglogredis
  • 3 3 Answers
  • 93 Views
  • 0 Followers
  • 0
Answer
Share
  • Facebook
  • Report

3 Answers

  • Voted
  • Oldest
  • Recent
  1. monkey Enlightened
    2022-07-28T01:24:29+00:00Added an answer on July 28, 2022 at 1:24 am
    This answer was edited.

    Đầu tiên thì cần hiểu 1 chút về HyperLogLogs em nhỉ? Thì theo như bài viết này: A HyperLogLog is a probabilistic data structure used in order to count unique things (technically this is referred to estimating the cardinality of a set). Usually counting unique items requires using an amount of memory proportional to the number of items you want to count, because you need to remember the elements you have already seen in the past in order to avoid counting them multiple times. However there is a set of algorithms that trade memory for precision: you end with an estimated measure with a standard error, which in the case of the Redis implementation is less than 1%. The magic of this algorithm is that you no longer need to use an amount of memory proportional to the number of items counted, and instead can use a constant amount of memory! 12k bytes in the worst case, or a lot less if your HyperLogLog (We’ll just call them HLL from now) has seen very few elements.

    Như vậy thì redis đã cài đặt 1 cấu trúc dữ liệu cho HyperLogLog để chuyên cho mục đích counting, và ưu điểm của nó là chỉ tốn tối đa 12KB bộ nhớ thôi. Ví dụ nếu như bình thường muốn count số lượng vote của 1 bài viết em sẽ cần map thế này: bài viết 1: setOf(user1, user2, user3) để cho ra count = 3, tuy nhiên khi em có hàng triệu user thì set kia nó sẽ lớn và em sẽ cần tốn hàng MB cho mỗi lần query, sẽ dễ gây out of memory. Tuy nhiên với HyperLogLog thì dù thế nào nó cũng chỉ tốn tối đa 12KB mà thôi.

    Tại sao không dùng incr?

    Bây giờ nếu em phải dùng incr thì em sẽ phải lưu thế nào?

    bài viết 1 | user1 | count = 1
    bài viết 1 | user2 | count = 1
    

    Hay

    user1 | bài viết 1 | count = 1
    user2 | bài viết 1 | count = 1
    

    Hay

    bài viết 1 | count = 123
    bài viết 2 | count = 456
    

    Cả 3 cách đều không được, riêng cách 3 thì có thể được, nhưng em sẽ phải sinh ra 1 con server riêng biệt (để tránh race) để kiểm tra thằng user nó đã vote chưa rồi mới incr lên được.

    Vậy nếu có 1 phương án gần đúng và nhẹ nhàng và sử dụng được trong môi trường nhiều server như HyperLogLog sẽ là giải pháp tốt hơn.

    Còn về stackask thì sao?

    Đối với những trang như stackask khi cơ sở dữ liệu còn bé (dưới vài triệu bản ghi) thì để cho đơn giản vẫn query từ MySQL thôi em ạ.

    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  2. Tuấn Vũ Đặng Beginner
    2022-07-28T03:08:10+00:00Added an answer on July 28, 2022 at 3:08 am

    Hi a Dũng, cảm ơn a đã trả lời bài viết.

    Em có thắc mắc đoạn “riêng cách 3 thì có thể được, nhưng em sẽ phải sinh ra 1 con server riêng biệt (để tránh race) để kiểm tra thằng user nó đã vote chưa rồi mới incr lên được.”

    Em chưa hiểu lắm tại sao phải dùng 1 con server riêng ạ.

    Ý em là mình có thể lưu đúng như a nói: post1|count = 123, mỗi lần có user view thì mình lại inc count lên post1|count = 124. Em nghĩ cái này quan trọng là lúc tăng phải tránh race vì 2 user có thể vào cùng 1 lúc,nhưng mà may là redit có single thread nên có support chỗ này : https://redis.io/commands/incr/. Một vấn đề nữa là với traffic lớn thì mình incr +1 liên tục vào 1 key như vậy thì redis có handle được không ạ.

    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
    • monkey Enlightened
      2022-07-28T03:23:19+00:00Replied to answer on July 28, 2022 at 3:23 am
      This answer was edited.

      Hãy giả sử em có 2 server, lúc này user sẽ gọi cùng lúc 2 api /api/v1/vote trên cả 2 server (do click đúp chẳng hạn). Thì lúc này em sẽ lư bản ghi user vote ở đâu đó (redis, db chẳng hạn) vậy thì trên cả 2 server có khả năng khi kiểm tra sẽ đề trả về user chưa vote, vậy thì biến count sẽ tăng lên 2 thay vì 1, vậy sẽ gây sai.

      Trên thực tế incr là phép tính đơn giản, nên anh nghĩ sẽ không có gì với traffic lớn cả.

      • 0
      • Share
        Share
        • Share on Facebook
        • Share on Twitter
        • Share on LinkedIn
        • Share on WhatsApp
        • Report

You must login to add an answer.

Continue with Google
Continue with Facebook
or use


Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 826
  • Answers 1k
  • Best Answers 80
  • Users 338
  • Popular
  • Answers
  • monkey

    [Deep Learning] Làm thế nào để xác định được cái ...

    • 16 Answers
  • Thành Vương

    Bug sai đường dẫn khi config ckeditor lên live

    • 14 Answers
  • Tú Trần Anh

    [Ezyfox Server] Unity game client không gửi được command khi ...

    • 12 Answers
  • tvd12
    tvd12 added an answer 1. Anh không hiểu tại sao em lại cần phải… February 4, 2023 at 7:50 am
  • tvd12
    tvd12 added an answer Cái này anh thấy là em đang gửi dữ liệu… February 4, 2023 at 7:46 am
  • monkey
    monkey added an answer Đây em: class Event{} class Room{} class EventRoom{eventId, roomId} February 2, 2023 at 9:07 am

Related Questions

  • tvd12

    Ý nghĩa của design pattern là gì?

    • 1 Answer
  • anaconda875

    momentjs aws-lambda wrong timezone

    • 2 Answers
  • anaconda875

    Sync to Async http request and response architecture

    • 1 Answer

Top Members

tvd12

tvd12

  • 76 Questions
  • 1k Points
Enlightened
monkey

monkey

  • 122 Questions
  • 1k Points
Enlightened
Nguyễn Thái Sơn

Nguyễn Thái Sơn

  • 205 Questions
  • 307 Points
Enlightened

Trending Tags

#formatdate .net .net core .net oop abstract class access app access token ai analytics android ansible anti-flooding apache poi api app architecture artificial intelligence assembly async asyncawait atomicboolean authentication backend backend nestjs background bash script batch bean big project binding bitcoin blockchain blog boot-nodes branch british btree bucket4j buffered build bundle c# c# .net cache caching callback career career path cast centos chat cloud cloud reliability commit communication company computer science concurrent config-css connection pool content-disposition contract convert date to number cookie cors cosmos cosmos-sdk crawl data cron css database database migration datasource datastructure deadlock decentralized exchange deep learning deploy contract design-pattern design patterns devops dex di distraction programing dns docker download draw.io du học duration dữ liệu lớn eclip editor elasticsearch email employee english erc20 erc721 estimation eth ethereum ethereum login excel exception exception handle exception handler executor export compliance extensions exyfox ezyfox ezyfox-boot ezyfox-server ezyfoxserver ezyhttp ezymq-kafka ezyredis facebook fe filter floating point flutter format json freetank french front-end frontend fullstack fulltextsearch future gallery game game-box game-room game-server gateway get get file zip git glide go golang google gorilla graduation thesis graphql grapql grpc guide h2 database handy terminal hazelcast hibernate hibernateconfig html http https hyperloglog image index indexing integration-test intellij interface interview io ioc ipfs isolate issue it java java core javacore javascript java spring javaw java web jenkins jetbrains job join jotform jpa js json json file jsonproperty json to object jsp jsp & servlet junit-test jvm jwt kafka keep promise kerberos keycloak kotlin language languague library list load-balancing load balancer lock log log4j log4j-core login lưu trữ machine learning macos mail mail template main maria db math maven merge message queue messaging metamask microservice microservices migration mobile model mongo monitoring mq msgpack multi-threading multiple tenant multithread multithreading mysql n naming naming convention nan netcore netty networking nft nft game nginx nio node.js nodejs non-blocking io null oop opensource optimize oracle orm otp message paginaiton pagination pancakeswap panic partition pdf pgpool phỏng vấn plugin pointer postgresql postman pre private_key procedure profile programming project management promise properties push-noti push message android push notification python python unicode qrcode question queue rabbitmq reactive reactjs reactjs download readmoretextview recyclerview redis refactor refresh token regex replica repository request resilence4j resource rest resttemplate roadmap ropssten ropsten round robin rust rxjava s3 schedule scheduled scheduled spring boot search security send email send mail server servlet session shift jis singleton sjis slack smart contract soap socket socket server soft delete solution sosanh spring spring-boot-test spring-jpa spring aop springboot spring boot spring data jpa spring redis springsecurity spring security springwebflux mysql spring websocket spring websocket cors sql sql server sse ssl email stackask storage stream stream api stress test structure trong spring boot study synchronize synchronized system environment variables test thread threadjava threadpool thread pool thymeleaf tomcat totp tracking location transaction transfer transfer git udp uniswap unit test unity upload upload file utf-8 file validate validate date vector view volatile vue vue cli watermark web web3 web3 client webassembly webflux webpack websocket windows 11 winforms work zip file zookeeper

Footer

Stack Ask

Stack Ask is where Developers Ask & Answers. It will help you resolve any questions and connect you with other people.

About Us

  • Meet The Team
  • About Us
  • Contact Us

Legal Stuff

  • Terms of Service
  • Privacy Policy
  • Cookie Policy

Help

Follow

© 2021 Stack Ask. All Rights Reserved
Powered by youngmonkeys.org