{"id":13878841,"url":"https://github.com/leandromoreira/redlock-rb","last_synced_at":"2025-05-14T12:10:48.178Z","repository":{"id":23113490,"uuid":"26467939","full_name":"leandromoreira/redlock-rb","owner":"leandromoreira","description":"Redlock is a redis-based distributed lock implementation in Ruby. More than 20M downloads.","archived":false,"fork":false,"pushed_at":"2024-08-02T03:31:51.000Z","size":229,"stargazers_count":709,"open_issues_count":23,"forks_count":83,"subscribers_count":8,"default_branch":"main","last_synced_at":"2025-05-11T05:02:18.234Z","etag":null,"topics":["distributed-locks","lock","redis","redlock","ruby"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-2-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/leandromoreira.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-11-11T03:35:22.000Z","updated_at":"2025-04-28T15:13:20.000Z","dependencies_parsed_at":"2024-01-13T20:46:03.334Z","dependency_job_id":"699612e9-532c-4943-9647-f50157e393ad","html_url":"https://github.com/leandromoreira/redlock-rb","commit_stats":{"total_commits":193,"total_committers":41,"mean_commits":"4.7073170731707314","dds":0.7772020725388601,"last_synced_commit":"fc3c5b1557a906b9651d575138c62a1da3086f8e"},"previous_names":[],"tags_count":31,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leandromoreira%2Fredlock-rb","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leandromoreira%2Fredlock-rb/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leandromoreira%2Fredlock-rb/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leandromoreira%2Fredlock-rb/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/leandromoreira","download_url":"https://codeload.github.com/leandromoreira/redlock-rb/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254140766,"owners_count":22021220,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["distributed-locks","lock","redis","redlock","ruby"],"created_at":"2024-08-06T08:02:01.663Z","updated_at":"2025-05-14T12:10:48.116Z","avatar_url":"https://github.com/leandromoreira.png","language":"Ruby","funding_links":[],"categories":["Ruby"],"sub_categories":[],"readme":"[![Build Status](https://github.com/leandromoreira/redlock-rb/actions/workflows/ci.yml/badge.svg)](https://github.com/leandromoreira/redlock-rb/actions/workflows/ci.yml)\n[![Coverage Status](https://coveralls.io/repos/leandromoreira/redlock-rb/badge.svg?branch=master)](https://coveralls.io/r/leandromoreira/redlock-rb?branch=master)\n[![Code Climate](https://codeclimate.com/github/leandromoreira/redlock-rb/badges/gpa.svg)](https://codeclimate.com/github/leandromoreira/redlock-rb)\n[![Gem Version](https://badge.fury.io/rb/redlock.svg)](http://badge.fury.io/rb/redlock)\n[![Inline docs](http://inch-ci.org/github/leandromoreira/redlock-rb.svg?branch=master)](http://inch-ci.org/github/leandromoreira/redlock-rb)\n\n\n# Redlock - A ruby distributed lock using redis.\n\n\u003e Distributed locks are a very useful primitive in many environments where different processes require to operate  with shared resources in a mutually exclusive way.\n\u003e\n\u003e There are a number of libraries and blog posts describing how to implement a DLM (Distributed Lock Manager) with Redis, but every library uses a different approach, and many use a simple approach with lower guarantees compared to what can be achieved with slightly more complex designs.\n\nThis is an implementation of a proposed [distributed lock algorithm with Redis](http://redis.io/topics/distlock). It started as a fork from [antirez implementation.](https://github.com/antirez/redlock-rb)\n\n## Compatibility\n\n* It works with Redis server versions 6.0 or later.\n* Redlock \u003e= 2.0 only works with [`RedisClient`](https://github.com/redis-rb/redis-client) client instance.\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'redlock'\n```\n\nAnd then execute:\n\n    $ bundle\n\nOr install it yourself as:\n\n    $ gem install redlock\n\n## Documentation\n\n[RubyDoc](http://www.rubydoc.info/gems/redlock/frames)\n\n## Usage example\n\n### Acquiring a lock\n\nNOTE: All expiration durations are in milliseconds.\n```ruby\n  # Locking\n  lock_manager = Redlock::Client.new([ \"redis://127.0.0.1:7777\", \"redis://127.0.0.1:7778\", \"redis://127.0.0.1:7779\" ])\n  first_try_lock_info = lock_manager.lock(\"resource_key\", 2000)\n  second_try_lock_info = lock_manager.lock(\"resource_key\", 2000)\n\n  p first_try_lock_info\n  # =\u003e {validity: 1987, resource: \"resource_key\", value: \"generated_uuid4\"}\n\n  p second_try_lock_info\n  # =\u003e false\n\n  # Unlocking\n  lock_manager.unlock(first_try_lock_info)\n\n  second_try_lock_info = lock_manager.lock(\"resource_key\", 2000)\n\n  p second_try_lock_info\n  # =\u003e {validity: 1962, resource: \"resource_key\", value: \"generated_uuid5\"}\n```\n\nThere's also a block version that automatically unlocks the lock:\n\n```ruby\nlock_manager.lock(\"resource_key\", 2000) do |locked|\n  if locked\n    # critical code\n  else\n    # error handling\n  end\nend\n```\n\nThere's also a bang version that only executes the block if the lock is successfully acquired, returning the block's value as a result, or raising an exception otherwise. Passing a block is mandatory.\n\n```ruby\nbegin\n  block_result = lock_manager.lock!(\"resource_key\", 2000) do\n    # critical code\n  end\nrescue Redlock::LockError\n  # error handling\nend\n```\n\n### Extending a lock\n\nTo extend the life of the lock:\n\n```ruby\nbegin\n  lock_info = lock_manager.lock(\"resource_key\", 2000)\n  while lock_info\n    # Critical code\n\n    # Time up and more work to do? Extend the lock.\n    lock_info = lock_manager.lock(\"resource key\", 3000, extend: lock_info)\n  end\nrescue Redlock::LockError\n  # error handling\nend\n```\n\nThe above code will also acquire the lock if the previous lock has expired and the lock is currently free. Keep in mind that this means the lock could have been acquired and released by someone else in the meantime. To only extend the life of the lock if currently locked by yourself, use the `extend_only_if_locked` parameter:\n\n```ruby\nlock_manager.lock(\"resource key\", 3000, extend: lock_info, extend_only_if_locked: true)\n```\n\n### Querying lock status\n\nYou can check if a resource is locked:\n\n```ruby\nresource = \"resource_key\"\nlock_info = lock_manager.lock(resource, 2000)\nlock_manager.locked?(resource)\n#=\u003e true\n\nlock_manager.unlock(lock_info)\nlock_manager.locked?(resource)\n#=\u003e false\n```\n\nAny caller can call the above method to query the status. If you hold a lock and would like to check if it is valid, you can use the `valid_lock?` method:\n\n```ruby\nlock_info = lock_manager.lock(\"resource_key\", 2000)\nlock_manager.valid_lock?(lock_info)\n#=\u003e true\n\nlock_manager.unlock(lock_info)\nlock_manager.valid_lock?(lock_info)\n#=\u003e false\n```\n\nThe above methods **are not safe if you are using this to time critical code**, since they return true if the lock has not expired, even if there's only (for example) 1ms left on the lock. If you want to safely time the lock validity, you can use the `get_remaining_ttl_for_lock` and `get_remaining_ttl_for_resource` methods.\n\nUse `get_remaining_ttl_for_lock` if you hold a lock and want to check the TTL specifically for your lock:\n```ruby\nresource = \"resource_key\"\nlock_info = lock_manager.lock(resource, 2000)\nsleep 1\n\nlock_manager.get_remaining_ttl_for_lock(lock_info)\n#=\u003e 986\n\nlock_manager.unlock(lock_info)\nlock_manager.get_remaining_ttl_for_lock(lock_info)\n#=\u003e nil\n```\n\nUse `get_remaining_ttl_for_resource` if you do not hold a lock, but want to know the remaining TTL on a locked resource:\n```ruby\n# Some part of the code\nresource = \"resource_key\"\nlock_info = lock_manager.lock(resource, 2000)\n\n# Some other part of the code\nlock_manager.locked?(resource)\n#=\u003e true\nlock_manager.get_remaining_ttl_for_resource(resource)\n#=\u003e 1975\n\n# Sometime later\nlock_manager.locked?(resource)\n#=\u003e false\nlock_manager.get_remaining_ttl_for_resource(resource)\n#=\u003e nil\n```\n\n## Redis client configuration\n\n`Redlock::Client` expects URLs, or configurations or Redis objects on initialization. Redis objects should be used for configuring the connection in more detail, i.e. setting username and password.\n\n```ruby\nservers = [ 'redis://localhost:6379', RedisClient.new(:url =\u003e 'redis://someotherhost:6379') ]\nredlock = Redlock::Client.new(servers)\n```\n\nTo utilize `Redlock::Client` with sentinels you can pass an instance of `RedisClient` or just a configuration hash as part of the servers array during initialization.\n\n```ruby\nconfig = {\n  name: \"mymaster\",\n  sentinels: [\n    { host: \"127.0.0.1\", port: 26380 },\n    { host: \"127.0.0.1\", port: 26381 },\n  ],\n  role: :master\n}\nclient = RedisClient.sentinel(**config).new_client\nservers = [ config, client ]\nredlock = Redlock::Client.new(servers)\n```\nRedlock supports the same configuration hash as `RedisClient`.\n\n## Redlock configuration\n\nIt's possible to customize the retry logic providing the following options:\n\n```ruby\n  lock_manager = Redlock::Client.new(\n                  servers, {\n                  retry_count:   3,\n                  retry_delay:   200, # milliseconds\n                  retry_jitter:  50,  # milliseconds\n                  redis_timeout: 0.1  # seconds\n                 })\n```\n\nIt is possible to associate `:retry_delay` option with `Proc` object. It will be called every time, with attempt number\nas argument, to get delay time value before next retry.\n\n```ruby\nretry_delay = proc { |attempt_number| 200 * attempt_number ** 2 } # delay of 200ms for 1st retry, 800ms for 2nd retry, etc.\nlock_manager = Redlock::Client.new(servers, retry_delay: retry_delay)\n```\n\nFor more information you can check [documentation](http://www.rubydoc.info/gems/redlock/Redlock%2FClient:initialize).\n\n## Run tests\n\nMake sure you have [docker installed](https://docs.docker.com/engine/installation/).\n\n    $ make\n\n## Disclaimer\n\nThis code implements an algorithm which is currently a proposal, it was not formally analyzed. Make sure to understand how it works before using it in your production environments. You can see discussion about this approach at [reddit](http://www.reddit.com/r/programming/comments/2nt0nq/distributed_lock_using_redis_implemented_in_ruby/) and also the [Antirez answers](http://antirez.com/news/101) for some critics.\n\n## Contributing\n\n1. [Fork it](https://github.com/leandromoreira/redlock-rb/fork)\n2. Create your feature branch (`git checkout -b my-new-feature`)\n3. Commit your changes (`git commit -am 'Add some feature'`)\n4. Push to the branch (`git push origin my-new-feature`)\n5. Create a new Pull Request\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleandromoreira%2Fredlock-rb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fleandromoreira%2Fredlock-rb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleandromoreira%2Fredlock-rb/lists"}