RedisQueuedLocks (aka RQL, aka RQL-lock) - distributed locks with "prioritized lock acquisition queue" capabilities based on the Redis Database.
Each lock request is put into the request queue (each lock is hosted by its own queue separately from other queues) and processed in order of their priority: requests of a higher priority go first, requests of the same priority are processed in FIFO order. Each lock request lives some period of time (RTTL) (with requeue capabilities) which guarantees the request queue will never be stacked.
In addition to the classic queued (FIFO) strategy RQL supports random (RANDOM) lock obtaining strategy when any acquirer from the lock queue can obtain the lock regardless the position in the queue.
Supports Read/Write locks, Reentrant locks, lock auto extending and lock request prioritization.
Provides flexible invocation flow, parametrized limits (lock request ttl, lock ttl, queue ttl, lock attempts limit, fast failing, etc), zombie locks elimination, lock indexing, logging and instrumentation (and much more).
For future features and updates check the ROADMAP section.
Table of Contents
- Requirements
- Experience
- Algorithm
- Installation
- Setup
- Configuration
- Usage
- lock
- lock!
- lock_series
- lock_series!
- lock_info
- queue_info
- locked?
- queued?
- unlock (aka
release_lock) - unlock_read (aka
release_read_lock) - clear_locks (aka
release_locks) - clear_locks_of (aka
release_locks_of) - clear_current_locks (aka
release_current_locks) - extend_lock_ttl
- locks
- queues
- keys
- locks_info
- queues_info
- clear_dead_requests
- reindex_locks
- current_acquirer_id
- current_host_id
- possible_host_ids
- Swarm Mode and Zombie Locks
- work and usage preview (temporary example-based docs)
- How to Swarm
- configuration
- swarm_status
- swarm_info
- swarmize!
- deswarmize!
- probe_hosts
- flush_zobmies
- zombies_info
- zombie_locks
- zombie_hosts
- zombie_acquirers
- Lock Index
- Lock Index Performance
- Lock Index Size
- Lock Access Strategies
- queued
- random
- Lock Request Prioritization
- Read/Write Locks
- Lock Auto Extending
- Manual Lock Lease extending from the running block of code
- Deadlocks and Reentrant locks
- Logging
- Logging Configuration
- Instrumentation
- Instrumentation Configuration
- Instrumentation Events
- "redis_queued_locks.lock_obtained"
- "redis_queued_locks.lock_obtaining_failed"
- "redis_queued_locks.extendable_reentrant_lock_obtained"
- "redis_queued_locks.reentrant_lock_obtained"
- "redis_queued_locks.lock_hold_and_release"
- "redis_queued_locks.reentrant_lock_hold_completes"
- "redis_queued_locks.lock_series_intermediate_lock_obtained"
- "redis_queued_locks.lock_series_lock_obtained"
- "redis_queued_locks.lock_series_lock_obtaining_failed"
- "redis_queued_locks.lock_series_obtained"
- "redis_queued_locks.lock_series_hold_and_release"
- "redis_queued_locks.lock_series_obtaining_failed"
- "redis_queued_locks.lock_auto_extended"
- "redis_queued_locks.lock_auto_extension_failed"
- "redis_queued_locks.auto_extended_lock_lost"
- "redis_queued_locks.lock_hold_limit_reached"
- "redis_queued_locks.lock_hold_limit_extended"
- "redis_queued_locks.explicit_lock_release"
- "redis_queued_locks.explicit_read_lock_release"
- "redis_queued_locks.explicit_all_locks_release"
- "redis_queued_locks.release_locks_of"
- "redis_queued_locks.extend_lock_ttl"
- "redis_queued_locks.clear_dead_requests"
- "redis_queued_locks.reindex_locks"
- Roadmap
- Build and Develop
- Contributing
- License
- Authors
Requirements
[back to top]
- Redis Version:
>= 7,~> 8.x; - Redis Protocol:
RESP3; - gem
redis-client:~> 0.20; - Ruby:
>= 4.0;
Experience
[back to top]
- Battle-tested on huge ruby projects in production:
~3000locks-per-second are obtained and released on an ongoing basis; - Works well with
hiredisdriver enabled (it is enabled by default on our projects whereredis_queued_locksare used);
Algorithm
[back to top]
Each lock request is put into the request queue (each lock is hosted by its own queue separately from other queues) and processed in order of their priority: requests of a higher priority go first, requests of the same priority are processed in FIFO order. Each lock request lives some period of time (RTTL) which guarantees that the request queue will never be stacked.
In addition to the classic "queued" (FIFO) strategy RQL supports "random" (RANDOM) lock obtaining strategy when any acquirer from the lock queue can obtain the lock regardless the position in the queue.
Soon: detailed explanation.
Installation
[back to top]
gem 'redis_queued_locks'bundle install
# --- or ---
gem install redis_queued_locksrequire 'redis_queued_locks'Setup
[back to top]
require 'redis_queued_locks'
# Step 1: initialize RedisClient instance
redis_client = RedisClient.config.new_pool # NOTE: provide your own RedisClient instance
# Step 2: initialize RedisQueuedLock::Client instance
rq_lock_client = RedisQueuedLocks::Client.new(redis_client) do |config|
# NOTE:
# - some your application-related configs;
# - for documentation see <Configuration> section in readme;
end
# Step 3: start to work with locks :)
rq_lock_client.lock("some-lock") { puts "Hello, lock!" }Configuration
[back to top]
redis_client = RedisClient.config.new_pool # NOTE: provide your own RedisClient instance
client = RedisQueuedLocks::Client.new(redis_client) do |config|
# (default: 3) (supports nil)
# - nil means "infinite retries" and you are only limited by the "try_to_lock_timeout" config;
config['retry_count'] = 3
# (milliseconds) (default: 200)
config['retry_delay'] = 200
# (milliseconds) (default: 25)
config['retry_jitter'] = 25
# (seconds) (supports nil)
# - nil means "no timeout" and you are only limited by "retry_count" config;
# - 0 is the same as nil (no timeout);
config['try_to_lock_timeout'] = 10
# (milliseconds) (default: 5_000)
# - lock's time to live
# - should be a positive Integer
config['default_lock_ttl'] = 5_000
# (seconds) (default: 15)
# - lock request timeout. after this timeout your lock request in queue will be requeued with new position (at the end of the
# lock requests of its priority);
# - (the enabled lock index) the lock request queue lives as long as its latest lock request (the queue TTL is refreshed with
# the queue ttl on each lock request): queues of dead acquirers expire by themselves;
# - should be a positive Integer
config['default_queue_ttl'] = 15
# (boolean) (default: false)
# - should be all blocks of code are timed by default;
config['is_timed_by_default'] = false
# (boolean) (default: false)
# - should the locks of all blocks of code be kept alive while the block is running by default
# (the `auto_extend:` option, see "Lock Auto Extending");
config['is_auto_extended_by_default'] = false
# (milliseconds) (default: nil)
# - how long an auto extended lock lives after each extension (the `auto_extend_ttl:` option,
# see "Lock Auto Extending");
# - `nil` means the ttl of the lock (`ttl:`);
# - should be `nil` or a positive Integer;
config['default_auto_extend_ttl'] = nil
# (milliseconds) (default: 3_600_000, 1 hour)
# - the protection against blocks of code that never finish: a block that hangs forever (an
# endless loop, a call without a timeout) or a block abandoned midway (a fiber that is never
# resumed: its `ensure` never runs and the lock is not released); such a block looks like a
# running one, and without a limit its lock is extended till the end of the process;
# - the limit of the auto extension of the lock (the `max_hold_time_during_auto_extend:` option, see
# "Lock Auto Extending");
# - `nil` means no limit;
# - !IMPORTANT: configure it yourself, deliberately, for your logic: `nil` (no limit) or a period
# that is longer than your longest block of code (a longer block of code loses its lock at the
# limit, a stuck block of code with `nil` holds its lock till the end of the process); the
# default is only a fallback;
# - should be `nil` or a positive Integer;
config['default_max_hold_time_during_auto_extend'] = 3_600_000
# (milliseconds) (default: 60_000)
# - the lock keeper thread (see "Lock Auto Extending") stops after this time without new blocks
# of code with `auto_extend: true` (and starts again on demand);
# - should be a positive Integer;
config['lock_keeper.idle_timeout'] = 60_000
# (milliseconds) (default: 100)
# - an idle lock keeper follows the rhythm of the extensions, but it does not wake up more often
# than this: a block of code with a shorter extension interval wakes it up by itself;
# - should be a positive Integer;
config['lock_keeper.min_idle_wake_up_interval'] = 100
# (integer) (default: 3)
# - a failed extension (Redis is not available, for example) is retried sooner:
# in `extension interval / extension_retry_ratio` (the extension interval is `auto_extend_ttl / 3`);
# - should be a positive Integer;
config['lock_keeper.extension_retry_ratio'] = 3
# (integer) (default: 10)
# - the locks that are due in `extension interval / extension_batching_ratio` are extended with
# the due ones: one pipeline instead of a wake-up per block of code;
# - should be a positive Integer;
config['lock_keeper.extension_batching_ratio'] = 10
# (milliseconds) (default: 10)
# - the schedule of the lock keeper is a set of slots of this length by the time of the next
# extension: a wake-up looks at the due slots only, not at all running blocks of code (the
# work of the keeper does not grow with the number of the running blocks of code);
# - should be a positive Integer;
config['lock_keeper.schedule_slot'] = 10
# (milliseconds) (default: 1_000)
# - a `timed` block of code of a fiber scheduler task (see "Lock Auto Extending") is interrupted
# through its fiber scheduler, and the interruption comes at the next suspension point of the
# fiber; when the block ends before it comes, the fiber waits for it this time at most (a
# scheduler that does not raise it in this time is not waited for anymore);
# - should be a positive Integer;
config['lock_keeper.fiber_interruption_timeout'] = 1_000
# (seconds) (default: 0.001)
# - the step of this wait (`Kernel#sleep`): each step suspends the fiber, so its scheduler gets
# the control and raises the interruption;
# - should be a positive Float or Integer;
config['lock_keeper.fiber_interruption_wait_step'] = 0.001
# NOTE: the `lock_keeper.*` settings are read when the lock keeper thread starts: a changed
# setting takes effect at the next start of the thread (after its idle timeout);
# (boolean) (default: false)
# - When the lock acquirement try reached the acquirement time limit (:timeout option) the
# `RedisQueuedLocks::LockAcquirementTimeoutError` is raised (when `raise_errors` option
# of the #lock method is set to `true`). The error message contains the lock key name and
# the timeout value).
# - <true> option adds the additional details to the error message:
# - current lock queue state (you can see which acquirer blocks your request and
# how much acquirers are in queue);
# - current lock data stored inside (for example: you can check the current acquirer and
# the lock meta state if you store some additional data there);
# - Realized as an option because of the additional lock data requires two additional Redis
# queries: (1) get the current lock from redis and (2) fetch the lock queue state;
# - These two additional Redis queries has async nature so you can receive
# inconsistent data of the lock and of the lock queue in your error emssage because:
# - required lock can be released after the error moment and before the error message build;
# - required lock can be obtained by other process after the error moment and
# before the error message build;
# - required lock queue can reach a state when the blocking acquirer start to obtain the lock
# and moved from the lock queue after the error moment and before the error message build;
# - You should consider the async nature of this error message and should use received data
# from error message correspondingly;
config['detailed_acq_timeout_error'] = false
# (symbol) (default: :queued)
# - Defines the way in which the lock should be obitained;
# - By default it is configured to obtain a lock in classic `queued` way:
# you should wait your position in queue in order to obtain a lock;
# - Can be customized in methods `#lock` and `#lock!` via `:access_strategy` attribute (see method signatures of #lock and #lock! methods);
# - Supports different strategies:
# - `:queued` (FIFO): the classic queued behavior (default), your lock will be obitaned if you are first in queue and the required lock is free;
# - `:random` (RANDOM): obtain a lock without checking the positions in the queue (but with checking the limist,
# retries, timeouts and so on). if lock is free to obtain - it will be obtained;
config['default_access_strategy'] = :queued
# (hash) (default: { lowest: -100, low: -50, normal: 0, high: 50, highest: 100 })
# - Lock request priority names: a priority name (Symbol) => its priority (Integer from `-100` to `100`);
# - The names can be used instead of the Integer priorities in the `:priority` attribute and in
# `config['default_lock_priority']`: `rql.lock('name', priority: :high) { ... }`;
# - Define the names of your application (keep the default names with `merge`):
# `config['lock_priorities'] = config['lock_priorities'].merge(payment: 90, email: -10)`;
# - The default value is frozen (it is shared by all clients): assign a new hash, don't change it in place;
# - See [Lock Request Prioritization](#lock-request-prioritization) documentation section for details;
config['lock_priorities'] = { lowest: -100, low: -50, normal: 0, high: 50, highest: 100 }
# (integer/symbol) (default: 0)
# - The default lock request priority: an Integer from `-100` (the lowest) to `100` (the highest)
# or a priority name of `config['lock_priorities']`;
# - The priority name should be a key of `config['lock_priorities']` (`RedisQueuedLocks::ConfigValidationError` otherwise):
# it is checked once after the configuration block (`Client.new { ... }`, `#configure { ... }`: the keys can be assigned
# in any order; an inconsistent pair is never applied: both keys keep their previous values, also when the block fails)
# and on a direct `config[...] =` assignment (before the value is applied: change the priority names and the default
# name together in a configuration block);
# - Can be customized in methods `#lock`, `#lock!`, `#lock_series` and `#lock_series!` via `:priority` attribute;
# - `:queued` access strategy: the lock request is placed in the lock request queue after all requests of the same
# or higher priority and before all requests of the lower priority (FIFO inside the same priority);
# - See [Lock Request Prioritization](#lock-request-prioritization) documentation section for details;
config['default_lock_priority'] = 0
# (symbol) (default: :wait_for_lock)
# - Global default conflict strategy mode;
# - Can be customized in methods `#lock` and `#lock!` via `:conflict_strategy` attribute (see method signatures of #lock and #lock! methods);
# - Conflict strategy is a logical behavior for cases when the process that obtained the lock want to acquire this lock again;
# - Realizes "reentrant locks" abstraction (same process conflict / same process deadlock);
# - By default uses `:wait_for_lock` strategy (classic way);
# - Strategies:
# - `:work_through` - continue working under the lock <without> lock's TTL extension;
# - `:extendable_work_through` - continue working under the lock <with> lock's TTL extension;
# - `:wait_for_lock` - (default) - work in classic way (with timeouts, retry delays, retry limits, etc - in classic way :));
# - `:dead_locking` - fail with deadlock exception;
# - See "Dead locks and Reentrant Locks" documentation section in README.md for details;
config['default_conflict_strategy'] = :wait_for_lock
# (default: 100)
# - how many items will be released at a time in #clear_locks and in #clear_dead_requests (uses SCAN);
# - (the enabled lock index) how many locks (lock names of the lock index) will be processed at a time
# (the ZSCAN count of the lock index pass);
# - affects the performance of your Redis and Ruby Application (configure thoughtfully);
# - should be a positive Integer
config['lock_release_batch_size'] = 100
# (default: 300)
# - how many items will be released at a time in #clear_locks_of and in #clear_current_locks methods (uses SCAN for batch extraction and DEL for batch deletion);
# - (the enabled lock index) how many locks (lock names of the lock index) will be processed at a time
# (the ZSCAN count of the lock index pass, DEL for batch deletion);
# - affects the ruby's memory (cuz this batch will be stored in Set object in first, and then will be splatted to the DEL redis method invocation) (configure thoughtfully);
# - affects the performance of your Redis (configure thoughtfully);
# - should be a positive Integer
config['clear_locks_of__lock_scan_size'] = 300
# (default: 300)
# - how many lock queues will be processed in one round trip in #clear_locks_of and in #clear_current_locks methods
# (lock queues are found by the same SCAN pass as locks or derived from the lock names of the same lock index pass);
# - affects the performance of your Redis (configure thoughtfully);
# - should be a positive Integer
config['clear_locks_of__queue_scan_size'] = 300
# (default: 500)
# - how many items should be extracted from redis during the #locks, #queues, #keys
# #locks_info, and #queues_info operations (uses SCAN);
# - (the enabled lock index) how many locks (lock names of the lock index) should be processed at a time
# (the ZSCAN count of the lock index pass);
# - affects the performance of your Redis and Ruby Application (configure thoughtfully);
# - should be a positive Integer
config['key_extraction_batch_size'] = 500
# (default: 1 day)
# - the default period of time (in milliseconds) after which a lock request is considered dead;
# - used for `#clear_dead_requests` as default vaule of `:dead_ttl` option;
config['dead_request_ttl'] = (1 * 24 * 60 * 60 * 1000) # one day in milliseconds
# (boolean) (default: false)
# - find locks via the lock index (`rql:index:locks`) instead of the full Redis keyspace `SCAN` in all lock-iterating operations
# (the swarm, #locks, #queues, #keys, #clear_locks, #clear_locks_of, #clear_dead_requests, ...);
# - the lock index is maintained by the lock acquirement itself only when it is enabled;
# - the client-wide mode (not a per-call option): use the same value on all your processes that share the Redis database;
# after enabling invoke `#reindex_locks` once (see the "Lock Index" documentation section);
config['lock_index_enabled'] = false
# (milliseconds) (default: 60_000)
# - the lock index grace period: the lock name stays in the lock index (`rql:index:locks`) for this period
# after the expiration of all its keys (see the "Lock Index" documentation section);
# - tolerance of the client clock skew between your hosts and of the network latency: should be greater than
# the maximal clock skew between your hosts plus the network latency;
# - used only with the enabled lock index (`config['lock_index_enabled']`);
config['lock_index_grace_period'] = 60_000
# (default: RedisQueuedLocks::Instrument::VoidNotifier)
# - instrumentation layer;
# - you can provide your own instrumenter that should realize `#notify(event, payload = {})` interface:
# - event: <string> requried;
# - payload: <hash> requried;
# - disabled by default via `VoidNotifier`;
config['instrumenter'] = RedisQueuedLocks::Instrument::ActiveSupport
# (default: -> { RedisQueuedLocks::Resource.calc_uniq_identity })
# - uniqude idenfitier that is uniq per process/pod;
# - prevents potential lock-acquirement collisions bettween different process/pods
# that have identical process_id/thread_id/fiber_id/ractor_id (identivcal acquirer ids);
# - it is calculated once per `RedisQueudLocks::Client` instance;
# - expects the proc object;
# - `SecureRandom.hex(8)` by default;
config['uniq_identifier'] = -> { RedisQueuedLocks::Resource.calc_uniq_identity }
# (default: RedisQueuedLocks::Logging::VoidLogger)
# - the logger object;
# - should implement `debug(progname = nil, &block)` (minimal requirement) or be an instance of Ruby's `::Logger` class/subclass;
# - supports `SemanticLogger::Logger` (see "semantic_logger" gem)
# - at this moment the only debug logs are realised in following cases:
# - "[redis_queued_locks.start_lock_obtaining]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.start_try_to_lock_cycle]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.dead_score_reached__reset_acquirer_position]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.lock_obtained]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
# - "[redis_queued_locks.lock_obtaining_failed]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time", "result");
# - "[redis_queued_locks.extendable_reentrant_lock_obtained]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
# - "[redis_queued_locks.reentrant_lock_obtained]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
# - "[redis_queued_locks.fail_fast_or_limits_reached_or_deadlock__dequeue]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.expire_lock]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.decrease_lock]" (logs "lock_key", "decreased_ttl", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.start_lock_series_obtaining]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.start_try_to_lock_series_cycle]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.dead_score_reached__reset_series_position]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.lock_series_intermediate_lock_obtained]" (logs "lock_key", "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
# - "[redis_queued_locks.lock_series_lock_obtained]" (logs "lock_key", "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
# - "[redis_queued_locks.lock_series_lock_obtaining_failed]" (logs "lock_key", "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time", "result");
# - "[redis_queued_locks.lock_series_obtained]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time", "reentrant_lock_keys");
# - "[redis_queued_locks.lock_series_obtaining_failed]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time", "result", "failed_lock_key");
# - "[redis_queued_locks.dequeue_from_lock_series_queues]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.expire_lock_series]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.decrease_lock_series]" (logs "lock_keys", "decreased_ttl", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.lock_auto_extended]" (logs "lock_key", "rw_mode", "ext_ttl", "rem_ttl", "acq_id", "hst_id");
# - "[redis_queued_locks.lock_auto_extension_failed]" (logs "lock_key", "rw_mode", "ext_ttl", "acq_id", "hst_id", "error");
# - "[redis_queued_locks.auto_extended_lock_lost]" (logs "lock_key", "rw_mode", "acq_id", "hst_id", "hold_time");
# - "[redis_queued_locks.lock_hold_limit_reached]" (logs "lock_key", "rw_mode", "max_hold_time_during_auto_extend", "acq_id", "hst_id");
# - "[redis_queued_locks.lock_hold_limit_extended]" (logs "lock_key", "rw_mode", "hold_time", "rem_hold_time", "ext_ttl", "rem_ttl", "acq_id", "hst_id");
# - "[redis_queued_locks.explicit_lock_release]" (logs "lock_key", "lock_key_queue", "rel_time", "at");
# - "[redis_queued_locks.explicit_read_lock_release]" (logs "lock_key", "acq_id", "lock_res", "rel_time", "at");
# - "[redis_queued_locks.explicit_all_locks_release]" (logs "at", "rel_time", "rel_key_cnt");
# - "[redis_queued_locks.release_locks_of]" (logs "at", "hst_id", "acq_id", "rel_time", "rel_key_cnt", "tch_queue_cnt");
# - "[redis_queued_locks.extend_lock_ttl]" (logs "lock_key", "rw_mode", "all_read_locks", "ext_ttl", "extended_locks_count", "ext_time", "at");
# - "[redis_queued_locks.clear_dead_requests]" (logs "dead_ttl", "prc_queue_cnt", "rel_time", "at");
# - "[redis_queued_locks.reindex_locks]" (logs "idx_key_cnt", "idx_time", "at");
# - "rw_mode" is the requested lock mode ('write'/'read'), the held lock mode for "expire_lock" and "decrease_lock",
# the mode of the series for lock series logs;
# - by default uses VoidLogger that does nothing;
config['logger'] = RedisQueuedLocks::Logging::VoidLogger
# (default: false)
# - adds additional debug logs;
# - enables additional logs for each internal try-retry lock acquiring (a lot of logs can be generated depending on your retry configurations);
# - it adds following debug logs in addition to the existing:
# - "[redis_queued_locks.try_lock.start]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.try_lock.rconn_fetched]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.try_lock.same_process_conflict_detected]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.try_lock.same_process_conflict_analyzed]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status");
# - "[redis_queued_locks.try_lock.reentrant_lock__extend_and_work_through]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status", "last_ext_ttl", "last_ext_ts");
# - "[redis_queued_locks.try_lock.reentrant_lock__work_through]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status", "last_spc_ts");
# - "[redis_queued_locks.try_lock.single_process_lock_conflict__dead_lock]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status", "last_spc_ts");
# - "[redis_queued_locks.try_lock.single_process_lock_conflict__lock_upgrade]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status", "last_spc_ts");
# - "[redis_queued_locks.try_lock.acq_added_to_queue]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.try_lock.remove_expired_acqs]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.try_lock.dead_request_removed]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "dead_acq_id", "dead_priority");
# - "[redis_queued_locks.try_lock.get_first_from_queue]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "first_acq_id_in_queue", "first_priority_in_queue");
# - "[redis_queued_locks.try_lock.exit__queue_ttl_reached]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.try_lock.exit__no_first]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "first_acq_id_in_queue", "first_priority_in_queue", "<current_lock_data>");
# - "[redis_queued_locks.try_lock.exit__lock_still_obtained]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "first_acq_id_in_queue", "first_priority_in_queue", "locked_by_acq_id", "<current_lock_data>");
# - "[redis_queued_locks.try_lock.exit__write_request_ahead]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "ahead_acq_id", "ahead_priority");
# - "[redis_queued_locks.try_lock.exit__read_request_ahead]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "ahead_acq_id", "ahead_priority");
# - "[redis_queued_locks.try_lock.exit__read_lock_still_obtained]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "first_acq_id_in_queue", "first_priority_in_queue");
# - "[redis_queued_locks.try_lock.exit__reentrant_lock_is_changed]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.try_lock.obtain__free_to_acquire]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "rw_mode" is the requested lock mode ('write'/'read');
config['log_lock_try'] = false
# (default: false)
# - enables <log sampling>: only the configured percent of RQL cases will be logged;
# - disabled by default;
# - works in tandem with <config['log_sampling_percent']> and <config['log_sampler']> configs;
config['log_sampling_enabled'] = false
# (default: 15)
# - the percent of cases that should be logged;
# - take an effect when <config['log_sampling_enabled']> is true;
# - works in tandem with <config['log_sampling_enabled']> and <config['log_sampler']> configs;
config['log_sampling_percent'] = 15
# (default: RedisQueuedLocks::Logging::Sampler)
# - percent-based log sampler that decides should be RQL case logged or not;
# - works in tandem with <config['log_sampling_enabled']> and <config['log_sampling_percent']> configs;
# - based on the ultra simple percent-based (weight-based) algorithm that uses SecureRandom.rand
# method so the algorithm error is ~(0%..13%);
# - you can provide your own log sampler with bettter algorithm that should realize
# `sampling_happened?(percent) => boolean` interface (see `RedisQueuedLocks::Logging::Sampler` for example);
config['log_sampler'] = RedisQueuedLocks::Logging::Sampler
# (default: false)
# - enables <instrumentaion sampling>: only the configured percent of RQL cases will be instrumented;
# - disabled by default;
# - works in tandem with <config['instr_sampling_percent'] and <config['instr_sampler']>;
config['instr_sampling_enabled'] = false
# (default: 15)
# - the percent of cases that should be instrumented;
# - take an effect when <config['instr_sampling_enabled']> is true;
# - works in tandem with <config['instr_sampling_enabled']> and <config['instr_sampler']> configs;
config['instr_sampling_percent'] = 15
# (default: RedisQueuedLocks::Instrument::Sampler)
# - percent-based log sampler that decides should be RQL case instrumented or not;
# - works in tandem with <config['instr_sampling_enabled']> and <config['instr_sampling_percent']> configs;
# - based on the ultra simple percent-based (weight-based) algorithm that uses SecureRandom.rand
# method so the algorithm error is ~(0%..13%);
# - you can provide your own log sampler with bettter algorithm that should realize
# `sampling_happened?(percent) => boolean` interface (see `RedisQueuedLocks::Instrument::Sampler` for example);
config['instr_sampler'] = RedisQueuedLocks::Instrument::Sampler
endUsage
[back to top]
- lock
- lock!
- lock_series
- lock_series!
- lock_info
- queue_info
- locked?
- queued?
- unlock (aka
release_lock) - unlock_read (aka
release_read_lock) - clear_locks (aka
release_locks) - clear_locks_of (aka
release_locks_of) - clear_current_locks (aka
release_current_locks) - extend_lock_ttl
- locks
- queues
- keys
- locks_info
- queues_info
- clear_dead_requests
- reindex_locks
- current_acquirer_id
- current_host_id
- possible_host_ids
The numeric options of the methods (ttls, timeouts, retries, scan and batch sizes, zombie ttl) are validated with the same
types and ranges as their config keys: Integer values only (timeout: 0.5 is rejected), RedisQueuedLocks::ArgumentError
(RedisQueuedLocks::SwarmArgumentError for the swarm methods) otherwise.
#lock - obtain a lock
[back to top]
-
#lock- obtain a lock; - If block is passed:
- the obtained lock will be released after the block execution or the lock's ttl (what will happen first);
- if you want to timeout (fail with timeout) the block execution with lock's TTL use
timed: trueoption; - (limitation) the write lock is released after the block without an owner check: if the block (without
timed: true) runs longer than the lock's ttl, the expired lock can be already obtained by another acquirer and the release deletes that lock (the same for the ttl decrease of:extendable_work_throughreentrant locks); useauto_extend: true(see Lock Auto Extending),timed: trueor extend the lock (#extend_lock_ttl) for long blocks (read locks are released per acquirer and are not affected);
- if you want to timeout (fail with timeout) the block execution with lock's TTL use
- the block's result will be returned;
- the obtained lock will be released after the block execution or the lock's ttl (what will happen first);
- If block is not passed:
- the obtained lock will be released after lock's ttl;
- the lock information will be returned (hash with technical info that contains: lock key, acquirer identifier, acquirement timestamp, lock's ttl, type of obtaining process, etc);
def lock(
lock_name,
ttl: config['default_lock_ttl'],
queue_ttl: config['default_queue_ttl'],
lock_index_grace_period: config['lock_index_grace_period'],
timeout: config['try_to_lock_timeout'],
timed: config['is_timed_by_default'],
auto_extend: config['is_auto_extended_by_default'],
auto_extend_ttl: config['default_auto_extend_ttl'],
max_hold_time_during_auto_extend: config['default_max_hold_time_during_auto_extend'],
retry_count: config['retry_count'],
retry_delay: config['retry_delay'],
retry_jitter: config['retry_jitter'],
raise_errors: false,
fail_fast: false,
conflict_strategy: config['default_conflict_strategy'],
rw_mode: :write,
access_strategy: config['default_access_strategy'],
priority: config['default_lock_priority'],
identity: uniq_identity, # (attr_accessor) calculated during client instantiation via config['uniq_identifier'] proc;
meta: nil,
detailed_acq_timeout_error: config['detailed_acq_timeout_error'],
instrument: nil,
instrumenter: config['instrumenter'],
logger: config['logger'],
log_lock_try: config['log_lock_try'],
log_sampling_enabled: config['log_sampling_enabled'],
log_sampling_percent: config['log_sampling_percent'],
log_sampler: config['log_sampler'],
log_sample_this: false,
instr_sampling_enabled: config['instr_sampling_enabled'],
instr_sampling_percent: config['instr_sampling_percent'],
instr_sampler: config['instr_sampler'],
instr_sample_this: false,
&block
)-
lock_name- (required)[String]- Lock name to be obtained.
-
ttl- (optional) - [Integer]- Lock's time to live (in milliseconds);
- should be a positive
Integer(write and read locks); - pre-configured in
config['default_lock_ttl'];
-
queue_ttl- (optional)[Integer]- Lifetime of the acuier's lock request. In seconds.
- (the enabled lock index) the lock request queue lives as long as its latest lock request (the queue TTL is refreshed on each lock request);
- pre-configured in
config['default_queue_ttl'];
-
lock_index_grace_period- (optional)[Integer]- The lock index grace period (in milliseconds): the lock name stays in the lock index for this period after the expiration of all its keys (tolerance of the client clock skew between your hosts and of the network latency);
- used only with the enabled lock index (
config['lock_index_enabled'], the client-wide mode); - see the Lock Index documentation section;
- pre-configured in
config['lock_index_grace_period'];
-
timeout- (optional)[Integer,NilClass]- Time period a client should try to acquire the lock (in seconds). Nil means "without timeout".
-
0is the same asnil(without timeout); - pre-configured in
config['try_to_lock_timeout']; - the timeout can not be swallowed by
rescueof your logger/instrumenter (seetimedbelow);
-
timed- (optiona)[Boolean]- Limit the invocation time period of the passed block of code by the lock's TTL.
- the block is interrupted by an internal
RedisQueuedLocks::Exception(an::Exception, likeTimeout::ExitExceptionof Ruby'sTimeout):rescue => e,rescue StandardError,rescue Timeout::Errorandrescue nilinside the block can not swallow it (onlyrescue Exception),ensureof the block still runs; - the block gets the lock's TTL minus the time from the start of the successful acquirement attempt and minus a 2 ms margin;
with no time left the block is not invoked (
RedisQueuedLocks::LockTtlTimeBudgetIsSpentError); - both failures have the common superclass
RedisQueuedLocks::TimedLockTimeoutError:RedisQueuedLocks::TimedBlockExceedsLockTtlError(the block exceeded the time) andRedisQueuedLocks::LockTtlTimeBudgetIsSpentError(the block was not invoked); - (limitation)
timedcan only interrupt the block: a longensureof the block,rescue Exceptionin the block and the code that can not be interrupted (a C extension holding the GVL) can outlive the lock; - with
auto_extend: truethe block is limited bymax_hold_time_during_auto_extendinstead of the lock's TTL and it is interrupted when the lock is lost (see Lock Auto Extending):RedisQueuedLocks::TimedBlockExceedsMaxHoldTimeErrorandRedisQueuedLocks::TimedBlockLostLockError(both areRedisQueuedLocks::TimedLockTimeoutErrorsubclasses); - pre-configured in
config['is_timed_by_default']; -
falseby default;
-
auto_extend- (optional)[Boolean]- Keep the lock alive while the passed block of code is running: the block can run longer than the lock's TTL, and the crash of the process releases the lock by the TTL. See Lock Auto Extending;
- has no effect without a block of code;
- pre-configured in
config['is_auto_extended_by_default']; -
falseby default;
-
auto_extend_ttl- (optional)[Integer,NilClass]- How long the lock lives after each auto extension (in milliseconds): it is the time from the moment of the extension, not a sum;
-
nilmeans the lock's TTL (ttl); - pre-configured in
config['default_auto_extend_ttl']; -
nilby default;
-
max_hold_time_during_auto_extend- (optional)[Integer,NilClass]- The protection of an auto extended lock against blocks of code that never finish: a block that hangs forever (an endless loop, a call without a timeout)
or a block abandoned midway (a fiber that is never resumed: its
ensurenever runs and the lock is not released). Such a block looks like a running one, and without a limit its lock is extended till the end of the process; - the limit of the auto extension (in milliseconds, from the start of the successful acquirement attempt): the lock of such a block of code expires by this time;
-
!IMPORTANT: configure it yourself, deliberately, for your logic (per call or in
config['default_max_hold_time_during_auto_extend']):nil(no limit) or a period that is longer than your longest block of code. A block of code that runs longer loses its lock at the limit (atimedblock is interrupted) unless it moves the limit bylease.hold_for, and a stuck block of code withnilholds its lock till the end of the process. The default (1 hour) is only a fallback; - should not be less than
ttlfor an auto extended lock; -
nilmeans no limit; - pre-configured in
config['default_max_hold_time_during_auto_extend']; -
3_600_000(1 hour) by default;
- The protection of an auto extended lock against blocks of code that never finish: a block that hangs forever (an endless loop, a call without a timeout)
or a block abandoned midway (a fiber that is never resumed: its
-
retry_count- (optional)[Integer,NilClass]- How many times we should try to acquire a lock. Nil means "infinite retries".
- pre-configured in
config['retry_count'];
-
retry_delay- (optional)[Integer]- A time-interval between the each retry (in milliseconds).
- pre-configured in
config['retry_delay'];
-
retry_jitter- (optional)[Integer]- Time-shift range for retry-delay (in milliseconds);
- pre-configured in
config['retry_jitter'];
-
instrumenter- (optional)[#notify]- See RedisQueuedLocks::Instrument::ActiveSupport for example;
- See Instrumentation section of docs;
- pre-configured in
config['instrumenter']with void notifier (RedisQueuedLocks::Instrument::VoidNotifier);
-
instrument- (optional)[NilClass,Any]- Custom instrumentation data wich will be passed to the instrumenter's payload with :instrument key;
-
nilby default (means "no custom instrumentation data");
-
raise_errors- (optional)[Boolean]- Raise errors on library-related limits (such as timeout or retry count limit) and on lock conflicts (such as same-process dead locks);
-
falseby default;
-
fail_fast- (optional)[Boolean]- Should the required lock to be checked before the try and exit immidietly if lock is already obtained;
- Should the logic exit immidietly after the first try if the lock was obtained by another process while the lock request queue was initially empty;
-
falseby default;
-
access_strategy- (optional) -[Symbol]- Defines the way in which the lock should be obitained (in queued way, in random way and so on);
- By default it is configured to obtain a lock in classic
:queuedway: you should wait your position in queue in order to obtain a lock; - Supports following strategies:
-
:queued(FIFO): (default) the classic queued behavior, your lock will be obitaned if you are first in queue and the required lock is free; -
:random(RANDOM): obtain a lock without checking the positions in the queue (but with checking the limist, retries, timeouts and so on). if lock is free to obtain - it will be obtained;
-
- pre-configured in
config['default_access_strategy']; - See Lock Access Strategies documentation section for details;
-
priority- (optional) -[Integer,Symbol]- The lock request priority: an Integer from
-100(the lowest) to100(the highest),0by default, or a priority name ofconfig['lock_priorities'](:lowest,:low,:normal,:high,:highestby default, the names of your application can be configured); -
:queuedaccess strategy: the lock request is placed in the lock request queue after all requests of the same or higher priority and before all requests of the lower priority (strict priority, FIFO inside the same priority; read and write lock requests too); -
:randomaccess strategy: the lock request does not wait for its turn (it ignores the order of the lock request queues and the priorities of other requests), but it is queued at the position of its priority like a:queuedone::queuedlock requests wait for it; - the obtained lock is never taken away: the priority orders the waiting lock requests only;
- pre-configured in
config['default_lock_priority']; - See Lock Request Prioritization documentation section for details;
- The lock request priority: an Integer from
-
conflict_strategy- (optional) -[Symbol]- The conflict strategy mode for cases when the process that obtained the lock want to acquire this lock again;
- By default uses
:wait_for_lockstrategy; - pre-confured in
config['default_conflict_strategy']; - Strategies:
-
:work_through- continue working under the lock without lock's TTL extension; -
:extendable_work_through- continue working under the lock with lock's TTL extension; -
:wait_for_lock- (default) - work in classic way (with timeouts, retry delays, retry limits, etc - in classic way :)); -
:dead_locking- fail with deadlock exception;
-
- See Deadlocks and Reentrant locks documentation section for details;
-
rw_mode- (optional) -[Symbol]- The lock mode (read/write lock semantics);
-
:writeby default; - Modes:
-
:write- exclusive lock: waits for the write lock and for all read locks; -
:read- shared lock: waits for the write lock only (read locks do not block each other);
-
- See Read/Write Locks documentation section for details;
-
identity- (optional)[String]- An unique string that is unique per
RedisQueuedLock::Clientinstance. Resolves the collisions between the same process_id/thread_id/fiber_id/ractor_id identifiers on different pods or/and nodes of your application; - It is calculated once during
RedisQueuedLock::Clientinstantiation and stored in@uniq_identityivar (accessed viauniq_dentityaccessor method); - Identity calculator is pre-configured in
config['uniq_identifier'];
- An unique string that is unique per
-
meta- (optional)[NilClass,Hash<String|Symbol,Any>]- A custom metadata wich will be passed to the lock data in addition to the existing data;
- Custom metadata can not contain reserved lock data keys (such as
lock_key,acq_id,ts,ini_ttl,rem_ttl,rw_mode); -
nilby default (means "no metadata");
-
detailed_acq_timeout_error- (optional)[Boolean]- When the lock acquirement try reached the acquirement time limit (:timeout option) the
RedisQueuedLocks::LockAcquirementTimeoutErroris raised (whenraise_errorsoption set totrue). The error message contains the lock key name and the timeout value). - option adds the additional details to the error message:
- current lock queue state (you can see which acquirer blocks your request and how much acquirers are in queue);
- current lock data stored inside (for example: you can check the current acquirer and the lock meta state if you store some additional data there);
- Realized as an option because of the additional lock data requires two additional Redis queries: (1) get the current lock from redis and (2) fetch the lock queue state;
- These two additional Redis queries has async nature so you can receive
inconsistent data of the lock and of the lock queue in your error emssage because:
- required lock can be released after the error moment and before the error message build;
- required lock can be obtained by other process after the error moment and before the error message build;
- required lock queue can reach a state when the blocking acquirer start to obtain the lock and moved from the lock queue after the error moment and before the error message build;
- You should consider the async nature of this error message and should use received data from error message correspondingly;
- pre-configred in
config['detailed_acq_timeout_error'];
- When the lock acquirement try reached the acquirement time limit (:timeout option) the
-
logger- (optional)[::Logger,#debug]- Logger object used for loggin internal mutation oeprations and opertioan results / process progress;
- pre-configured in
config['logger']with void loggerRedisQueuedLocks::Logging::VoidLogger;
-
log_lock_try- (optional)[Boolean]- should be logged the each try of lock acquiring (a lot of logs can be generated depending on your retry configurations);
- pre-configured in
config['log_lock_try']; -
falseby default;
-
log_sampling_enabled- (optional)[Boolean]- enables log sampling: only the configured percent of RQL cases will be logged;
- disabled by default;
- works in tandem with
log_sampling_percentandlog_sampleroptions; - pre-configured in
config['log_sampling_enabled'];
-
log_sampling_percent- (optional)[Integer]- the percent of cases that should be logged;
- take an effect when
log_sampling_enabledis true; - works in tandem with
log_sampling_enabledandlog_sampleroptions; - pre-configured in
config['log_sampling_percent'];
-
log_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Logging::Sampler>]- percent-based log sampler that decides should be RQL case logged or not;
- works in tandem with
log_sampling_enabledandlog_sampling_percentoptions; - based on the ultra simple percent-based (weight-based) algorithm that uses SecureRandom.rand method so the algorithm error is ~(0%..13%);
- you can provide your own log sampler with bettter algorithm that should realize
sampling_happened?(percent) => booleaninterface (seeRedisQueuedLocks::Logging::Samplerfor example); - pre-configured in
config['log_sampler'];
-
log_sample_this- (optional)[Boolean]- marks the method that everything should be logged despite the enabled log sampling;
- makes sense when log sampling is enabled;
-
falseby default;
-
instr_sampling_enabled- (optional)[Boolean]- enables instrumentaion sampling: only the configured percent of RQL cases will be instrumented;
- disabled by default;
- works in tandem with
instr_sampling_percentandinstr_sampleroptions; - pre-configured in
config['instr_sampling_enabled'];
-
instr_sampling_percent- (optional)[Integer]- the percent of cases that should be instrumented;
- take an effect when
instr_sampling_enabledis true; - works in tandem with
instr_sampling_enabledandinstr_sampleroptions; - pre-configured in
config['instr_sampling_percent'];
-
instr_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Instrument::Sampler>]- percent-based log sampler that decides should be RQL case instrumented or not;
- works in tandem with
instr_sampling_enabledandinstr_sampling_percentoptions; - based on the ultra simple percent-based (weight-based) algorithm that uses SecureRandom.rand method so the algorithm error is ~(0%..13%);
- you can provide your own log sampler with bettter algorithm that should realize
sampling_happened?(percent) => booleaninterface (seeRedisQueuedLocks::Instrument::Samplerfor example); - pre-configured in
config['instr_sampler'];
-
instr_sample_this- (optional)[Boolean]- marks the method that everything should be instrumneted despite the enabled instrumentation sampling;
- makes sense when instrumentation sampling is enabled;
-
falseby default;
-
block- (optional)[Block]- A block of code that should be executed after the successfully acquired lock.
- If block is passed the obtained lock will be released after the block execution or its ttl (what will happen first);
- If block is not passed the obtained lock will be released after its ttl;
- If you want the block to have a TTL too and this TTL to be the same as TTL of the lock
use
timed: trueoption (rql.lock("my_lock", timed: true, ttl: 5_000) { ... })
Return value:
- If block is passed the block's yield result will be returned:
result = rql.lock("my_lock") { 1 + 1 } result # => 2
- If block is not passed the lock information will be returned:
result = rql.lock("my_lock") result # => { ok: true, result: { lock_key: "rql:lock:my_lock", acq_id: "rql:acq:26672/2280/2300/2320/70ea5dbf10ea1056", hst_id: "rql:hst:26672/2280/2320/70ea5dbf10ea1056", ts: 1711909612.653696, ttl: 10000, process: :lock_obtaining } }
- Lock information result:
-
Signature:
[yield, Hash<Symbol,Boolean|Hash<Symbol,Numeric|String>>] -
Format:
{ ok: true/false, result: <Symbol|Hash<Symbol,Hash>> }; -
Includes the
:processkey that describes a logical type of the lock obtaining process. Possible values:-
:lock_obtaining- classic lock obtaining proces. Default behavior (conflict_strategy: :wait_for_lock); -
:extendable_conflict_work_through- reentrant lock acquiring process with lock's TTL extension. Suitable forconflict_strategy: :extendable_work_through; -
:conflict_work_through- reentrant lock acquiring process without lock's TTL extension. Suitable forconflict_strategy: :work_through; - (
conflict_strategy: :dead_lockingdoes not obtain the lock already obtained by the current acquirer: it fails with{ ok: false, result: :conflict_dead_lock }); - For more details see Deadlocks and Reentrant locks readme section;
-
-
For successful lock obtaining:
{ ok: true, result: { lock_key: String, # acquirerd lock key ("rql:lock:your_lock_name") acq_id: String, # acquirer identifier ("process_id/thread_id/fiber_id/ractor_id/identity") hst_id: String, # host identifier ("process_id/thread_id/ractor_id/identity") ts: Float, # time (epoch) when lock was obtained (float, Time#to_f) ttl: Integer, # lock's time to live in milliseconds (integer) process: Symbol # which logical process has acquired the lock (:lock_obtaining, :extendable_conflict_work_through, :conflict_work_through) } }
# example: { ok: true, result: { lock_key: "rql:lock:my_lock", acq_id: "rql:acq:26672/2280/2300/2320/70ea5dbf10ea1056", hst_id: "rql:hst:26672/2280/2320/70ea5dbf10ea1056", ts: 1711909612.653696, ttl: 10000, process: :lock_obtaining # for reentrant locks (conflict strategies): :conflict_work_through, :extendable_conflict_work_through } }
-
For failed lock obtaining:
{ ok: false, result: :timeout_reached } # see <timeout> option { ok: false, result: :retry_limit_reached } # see <retry_count> option { ok: false, result: :conflict_dead_lock } # see <conflict_strategy> option for details (:dead_locking strategy) { ok: false, result: :conflict_lock_upgrade } # read-to-write lock upgrade (see <rw_mode> and <conflict_strategy> options) { ok: false, result: :fail_fast_no_try } # see <fail_fast> option { ok: false, result: :fail_fast_after_try } # see <fail_fast> option
-
Examples:
- obtain a lock:
rql.lock("my_lock") { print "Hello!" }- obtain a lock with custom lock TTL:
rql.lock("my_lock", ttl: 5_000) { print "Hello!" } # for 5 seconds- obtain a lock and limit the passed block of code TTL with lock's TTL:
rql.lock("my_lock", ttl: 5_000, timed: true) { sleep(4) }
# => OK
rql.lock("my_lock", ttl: 5_000, timed: true) { sleep(6) }
# => fails with RedisQueuedLocks::TimedBlockExceedsLockTtlError (a RedisQueuedLocks::TimedLockTimeoutError)- infinite lock obtaining (no retry limit, no timeout limit):
rql.lock("my_lock", retry_count: nil, timeout: nil)- try to obtain with a custom waiting timeout:
# First Ruby Process:
rql.lock("my_lock", ttl: 5_000) { sleep(4) } # acquire a long living lock
# Another Ruby Process:
rql.lock("my_lock", timeout: 2) # try to acquire but wait for a 2 seconds maximum
# =>
{ ok: false, result: :timeout_reached }- obtain a lock and immediatly continue working (the lock will live in the background in Redis with the passed ttl)
rql.lock("my_lock", ttl: 6_500) # blocks execution until the lock is obtained
puts "Let's go" # will be called immediately after the lock is obtained- add custom metadata to the lock (via
:metaoption):
rql.lock("my_lock", ttl: 123456, meta: { "some" => "data", key: 123.456 })
rql.lock_info("my_lock")
# =>
{
"lock_key" => "rql:lock:my_lock",
"rw_mode" => "write",
"acq_id" => "rql:acq:123/456/567/678/374dd74324",
"hst_id" => "rql:hst:123/456/678/374dd74324",
"ts" => 123456789,
"ini_ttl" => 123456,
"rem_ttl" => 123440,
"some" => "data",
"key" => "123.456" # NOTE: returned as a raw string directly from Redis
}- (
:queue_ttl) setting a short limit of time to the lock request queue position (if a process fails to acquire the lock within this period of time (and before timeout/retry_count limits occurs of course) - its lock request will be moved to the end of queue: the end of the lock requests of its priority):
rql.lock("my_lock", queue_ttl: 5, timeout: 10_000, retry_count: nil)
# "queue_ttl: 5": 5 seconds time slot before the lock request moves to the end of queue;
# "timeout" and "retry_count" is used as "endless lock try attempts" example to show the lock queue behavior;
# lock queue: =>
[
"rql:acq:123/456/567/676/374dd74324",
"rql:acq:123/456/567/677/374dd74322", # <- long living lock
"rql:acq:123/456/567/679/374dd74321",
"rql:acq:123/456/567/683/374dd74322", # <== we are here
"rql:acq:123/456/567/685/374dd74329", # some other waiting process
]
# ... some period of time (2 seconds later)
# lock queue: =>
[
"rql:acq:123/456/567/677/374dd74322", # <- long living lock
"rql:acq:123/456/567/679/374dd74321",
"rql:acq:123/456/567/683/374dd74322", # <== we are here
"rql:acq:123/456/567/685/374dd74329", # some other waiting process
]
# ... some period of time (3 seconds later)
# ... queue_ttl time limit is reached
# lock queue: =>
[
"rql:acq:123/456/567/685/374dd74329", # some other waiting process
"rql:acq:123/456/567/683/374dd74322", # <== we are here (moved to the end of the queue)
]- obtain a lock in
:randomway (with:randomstrategy): in:randomstrategy any acquirer from the lock queue can obtain the lock regardless of the position in the lock queue;
# Current Process (process#1)
rql.lock('my_lock', ttl: 2_000, access_strategy: :random)
# => holds the lock
# Another Process (process#2)
rql.lock('my_lock', retry_delay: 7000, ttl: 4000, access_strategy: :random)
# => the lock is not free, stay in a queue and retry...
# Another Process (process#3)
rql.lock('my_lock', retry_delay: 3000, ttl: 3000, access_strategy: :random)
# => the lock is not free, stay in a queue and retry...
# lock queue:
[
"rql:acq:123/456/567/677/374dd74322", # process#1 (holds the lock)
"rql:acq:123/456/567/679/374dd74321", # process#2 (waiting for the lock, in retry)
"rql:acq:123/456/567/683/374dd74322", # process#3 (waiting for the lock, in retry)
]
# ... some period of time
# -> process#1 => released the lock;
# -> process#2 => delayed retry, waiting;
# -> process#3 => preparing for retry (the delay is over);
# lock queue:
[
"rql:acq:123/456/567/679/374dd74321", # process#2 (waiting for the lock, DELAYED)
"rql:acq:123/456/567/683/374dd74322", # process#3 (trying to obtain the lock, RETRYING now)
]
# ... some period of time
# -> process#2 => didn't have time to obtain the lock, delayed retry;
# -> process#3 => holds the lock;
# lock queue:
[
"rql:acq:123/456/567/679/374dd74321", # process#2 (waiting for the lock, DELAYED)
"rql:acq:123/456/567/683/374dd74322", # process#3 (holds the lock)
]
# `process#3` is the last in queue, but has acquired the lock because his lock request "randomly" came first;#lock! - exceptional lock obtaining
[back to top]
-
#lock!- exceptional lock obtaining; - fails when (and with):
- (
RedisQueuedLocks::LockAlreadyObtainedError) whenfail_fastistrueand lock is already obtained; - (
RedisQueuedLocks::LockAcquirementTimeoutError)timeoutlimit reached before lock is obtained; - (
RedisQueuedLocks::LockAcquirementRetryLimitError)retry_countlimit reached before lock is obtained; - (
RedisQueuedLocks::ConflictLockObtainError) whenconflict_strategy: :dead_lockingis used and the "same-process-dead-lock" is happened (see Deadlocks and Reentrant locks for details);
- (
def lock!(
lock_name,
ttl: config['default_lock_ttl'],
queue_ttl: config['default_queue_ttl'],
lock_index_grace_period: config['lock_index_grace_period'],
timeout: config['try_to_lock_timeout'],
timed: config['is_timed_by_default'],
auto_extend: config['is_auto_extended_by_default'],
auto_extend_ttl: config['default_auto_extend_ttl'],
max_hold_time_during_auto_extend: config['default_max_hold_time_during_auto_extend'],
retry_count: config['retry_count'],
retry_delay: config['retry_delay'],
retry_jitter: config['retry_jitter'],
fail_fast: false,
identity: uniq_identity,
meta: nil,
detailed_acq_timeout_error: config['detailed_acq_timeout_error']
logger: config['logger'],
log_lock_try: config['log_lock_try'],
instrument: nil,
instrumenter: config['instrumenter'],
access_strategy: config['default_access_strategy'],
priority: config['default_lock_priority'],
conflict_strategy: config['default_conflict_strategy'],
rw_mode: :write,
log_sampling_enabled: config['log_sampling_enabled'],
log_sampling_percent: config['log_sampling_percent'],
log_sampler: config['log_sampler'],
log_sample_this: false,
instr_sampling_enabled: config['instr_sampling_enabled'],
instr_sampling_percent: config['instr_sampling_percent'],
instr_sampler: config['instr_sampler'],
instr_sample_this: false,
&block
)See #lock method documentation.
#lock_series - acquire a series of locks
[back to top]
lock_series - obtain a group of locks atomically: all locks of the series are obtained at the same moment with the same TTL
and are held together while your block of code is executing (or, if a block is not passed, while the locks live).
Guarantees:
- all or nothing: one transaction obtains all locks of the series; an attempt that can not obtain some lock obtains nothing, so a failed series leaves no obtained locks (and no lock requests in the lock queues);
-
all locks at the same time: all locks are obtained with the same TTL (
ttl:) at the same moment, so the block of code never works with a partially held series andtimed: truelimits it by the real lifetime of the locks; - no hold-and-wait: nothing is held while the series waits for its locks: the free locks of the series are not locked and their TTL is not spent on the waiting;
-
no deadlocks between lock series: the order of the lock names does not matter (
lock_series("a", "b")andlock_series("b", "a")work in parallel threads): the lock request of the series has one position in all its lock queues, so the lock requests wait only for earlier lock requests. Your own nested logic is out of it: code that holds a lock and then waits for a series still can wait for a lock that is needed by another acquirer (the waiting is limited by the limits of the series);
How the options work:
- method options are the same as for the
#lockmethod:ttl,queue_ttl,retry_count,retry_delay,retry_jitter, etc; - limits are the limits of the whole series, not of each lock:
timeout:is one time period for all locks,retry_count:is the number of attempts to obtain all locks,queue_ttl:is the lifetime of the lock request of the series; -
ttl:is the TTL of each lock of the series (the same value for all locks); -
rw_mode:is the same for all locks of the series (see Read/Write Locks); -
priority:is the same for all locks of the series (see Lock Request Prioritization): the lock request of the series has this priority in all its lock queues; -
conflict_strategy:works per lock: reentrant locks (already obtained by your outer logic,:work_through/:extendable_work_through) are not obtained and not released by the series: the extended ones (:extendable_work_through) get their TTL back after the block, like in the#lockmethod; a lock with a failed conflict (:dead_locking, read-to-write lock upgrade) fails the whole series; -
fail_fast: truefails the series on the first lock that is already obtained; - a duplicated lock name is the same lock (
lock_series("a", "b", "a")works with two locks); at least one lock name is required (RedisQueuedLocks::ArgumentError);
Details and limitations:
- when your block of code has completed its execution (with or without an exception) all locks obtained by the series are released;
- an interrupted series (
Timeout.timeoutof your logic,Thread#kill, a Redis error) releases its locks and drops its lock requests, when it is possible (a dead process or an unavailable Redis: the locks live till their TTL, the lock requests till theirqueue_ttl); - the series releases only locks obtained by itself and only if they are still owned by the current acquirer: a lock that is expired during your block and obtained by another acquirer is kept;
- if you did not pass a block - all locks live till their TTL;
- locks of the series are regular locks with regular keys:
#lock_info,#unlock,#extend_lock_ttl,#clear_locksand the swarm work with each of them separately; -
:queuedaccess strategy: a series that is ahead of other lock requests makes them wait even for its free locks (the waiting series is the next obtainer of these locks): one long-waiting series delays the lock requests of all its locks for its waiting time (no longer than itsqueue_ttl,timeoutandretry_countlimits allow); -
:randomaccess strategy: the series is obtained only when all its locks are free at the same moment, so a big series can wait for a long time under load (lock requests of the:randomstrategy have no reserved turn); - all processes that work with the same locks should use the same RQL version: older versions obtain the series lock by lock;
How to use:
- method signature is the same as the
#lock;
# typical logic-oriented way
client.lock_series("a", "b", "c") { ...some_code... }
# result-oriented way:
# - (block is not passed)
client.lock_series('x', 'y', 'z', ttl: 5_000)
# =>
{
ok: true,
result: {
lock_series: ["x", "y", "z"], # your locks
rql_lock_series: ["rql:lock:x", "rql:lock:y", "rql:lock:z"], # internal RQL lock-keys of your locks
acq_id: "rql:acq:4486/1696/1704/1712/e6fd0da7991e4303", # the acquirer of the locks
hst_id: "rql:hst:4486/1696/1712/e6fd0da7991e4303", # the host of the locks
ts: 1769506100.676884, # the time when the locks were obtained, epoch
ttl: 5000 # the ttl of each lock, milliseconds
}
}
# - (detailed result, block is passed)
detailed_result = client.lock_series('x', 'y', 'z', detailed_result: true) { 1 + 2 }
detailed_result # =>
{
yield_result: 3, # result of your block of code
locks_release_strategy: :immediate_release_after_yield, # (block is passed)
locks_released_at: 1769506100.676884, # (instrumentation) release time, epoch
locks_acq_time: 7.0, # (instrumentation) time spent to acquire all locks, milliseconds
locks_hold_time: 0.65, # (instrumentation) lock series hold period (hold preiod of all required locks), milliseconds
lock_series: ["x", "y", "z"], # your locks
rql_lock_series: ["rql:lock:x", "rql:lock:y", "rql:lock:z"] # internal RQL lock-keys of your locks
}
# - (detailed result, block is not passed)
detailed_result = client.lock_series('x', 'y', 'z', detailed_result: true)
detailed_result # =>
{
yield_result: nil, # block is not given - nothing to return
locks_release_strategy: :redis_key_ttl, # block is not given - locks are living in redis with their TTL
locks_released_at: nil, # (instrumentation) # block is not given - locks are living in redis with their TTL
locks_acq_time: 7.0, # (instrumentation) time spent to acquire all locks, milliseconds
locks_hold_time: nil, # (instrumentation) # block is not given - locks are living in redis with their TTL
lock_series: ["x", "y", "z"], # your locks
rql_lock_series: ["rql:lock:x", "rql:lock:y", "rql:lock:z"] # internal RQL lock-keys of your locks
}# (failed lock obtainig) when lock series can not be obtained for some reasons
# for example: one of required lock in series is still obtained and can not be obtained now (and all retries are exhausted)
# - lock 'a' is obtained with long ttl
client.lock('a', ttl: 10_000_000)
# - try to bobtain series of locks with `a` inside the series (`a` can not be obtained for now)
client.lock_series('c', 'a', 'b') # ... `a` is still obtained
# =>
{
ok: false,
result: {
error: :failed_to_acquire_lock_series,
detailed_errors: { 'a' => { ok: false, result: :retry_limit_reached } }, # (empty without `failed_on_lock`)
lock_series: ["c", "a", "b"],
acquired_locks: [], # always empty: nothing is obtained by the failed series
missing_locks: ["c", "a", "b"],
failed_on_lock: "a", # the first lock that blocked the last completed attempt (`nil`: unknown)
}
}Instrumentation events:
-
rw_modeis the mode of the series (the same for all locks of the series); -
#lockevents (lock_obtained,lock_obtaining_failed, ...) are not raised for the locks of the series, each lock has its own series events with the series context in the name (lock_keyis the lock,lock_keysare all locks of the series):-
lock_series_intermediate_lock_obtained- intermediate obtaining: the lock passed all checks of an attempt of the series (the lock is free and the lock request of the series is next). Nothing is held yet: the series can still wait for its other locks or fail. Raised once per lock of the series (not per attempt), in the order of the lock names up to the lock that blocks the series; -
lock_series_lock_obtained- full obtaining: the lock is really obtained, all locks of the series are held; -
lock_series_lock_obtaining_failed- the lock that blocked the failed series, once per series (not raised when the blocking lock is unknown: no attempt found it, seefailed_lock_keyoflock_series_obtaining_failed); - reentrant locks are not obtained by the series: they have no lock events (see
reentrant_lock_keysof the series events);
-
- see Instrumentation Events for the payload details;
# instrumentation events (examples)
"redis_queued_locks.lock_series_intermediate_lock_obtained" => # {lock_key: "rql:lock:s", lock_keys: ["rql:lock:s", "rql:lock:t"], rw_mode: :write, priority: 0, ttl: 5000, acq_id: "rql:acq:4486/1696/1704/1712/e6fd0da7991e4303", hst_id: "rql:hst:4486/1696/1712/e6fd0da7991e4303", ts: 1769627106.4688692, acq_time: 2.61, instrument: nil}
"redis_queued_locks.lock_series_lock_obtained" => # {lock_key: "rql:lock:s", lock_keys: ["rql:lock:s", "rql:lock:t"], rw_mode: :write, priority: 0, ttl: 5000, acq_id: "rql:acq:4486/1696/1704/1712/e6fd0da7991e4303", hst_id: "rql:hst:4486/1696/1712/e6fd0da7991e4303", ts: 1769627106.4688692, acq_time: 2.61, instrument: nil}
"redis_queued_locks.lock_series_lock_obtaining_failed" => # {lock_key: "rql:lock:y", lock_keys: ["rql:lock:x", "rql:lock:y"], rw_mode: :write, priority: 0, ttl: 5000, acq_id: "rql:acq:4486/1696/1704/1712/e6fd0da7991e4303", hst_id: "rql:hst:4486/1696/1712/e6fd0da7991e4303", ts: 1769627106.4717052, acq_time: 4.26, result: :retry_limit_reached, instrument: nil}
"redis_queued_locks.lock_series_obtained" => # {lock_keys: ["rql:lock:s", "rql:lock:t", "rql:lock:u"], rw_mode: :write, priority: 0, ttl: 5000, acq_id: "rql:acq:4486/1696/1704/1712/e6fd0da7991e4303", hst_id: "rql:hst:4486/1696/1712/e6fd0da7991e4303", ts: 1769627106.4688692, acq_time: 2.61, reentrant_lock_keys: [], instrument: nil}
"redis_queued_locks.lock_series_hold_and_release" => # {lock_keys: ["rql:lock:x", "rql:lock:y", "rql:lock:z"], rw_mode: :write, priority: 0, hold_time: 0.29, ttl: 5000, acq_id: "rql:acq:4486/1696/1704/1712/e6fd0da7991e4303", hst_id: "rql:hst:4486/1696/1712/e6fd0da7991e4303", ts: 1769627106.4717052, acq_time: 4.26, reentrant_lock_keys: [], instrument: nil}
"redis_queued_locks.lock_series_obtaining_failed" => # {lock_keys: ["rql:lock:x", "rql:lock:y"], rw_mode: :write, priority: 0, ttl: 5000, acq_id: "rql:acq:4486/1696/1704/1712/e6fd0da7991e4303", hst_id: "rql:hst:4486/1696/1712/e6fd0da7991e4303", ts: 1769627106.4717052, acq_time: 4.26, result: :retry_limit_reached, failed_lock_key: "rql:lock:y", instrument: nil}Logs:
-
rw_modeis the mode of the series (the same for all locks of the series); - see Logging for the logged keys;
# logs (examples)
[redis_queued_locks.start_lock_series_obtaining] lock_keys => '["rql:lock:a", "rql:lock:b"]' queue_ttl => 15 acq_id => 'rql:acq:4486/1696/1704/1712/e6fd0da7991e4303' hst_id => 'rql:hst:4486/1696/1712/e6fd0da7991e4303' acs_strat => 'queued' rw_mode => 'write' priority => 0
[redis_queued_locks.start_try_to_lock_series_cycle] lock_keys => '["rql:lock:a", "rql:lock:b"]' queue_ttl => 15 acq_id => 'rql:acq:4486/1696/1704/1712/e6fd0da7991e4303' hst_id => 'rql:hst:4486/1696/1712/e6fd0da7991e4303' acs_strat => 'queued' rw_mode => 'write' priority => 0
[redis_queued_locks.lock_series_intermediate_lock_obtained] lock_key => 'rql:lock:a' lock_keys => '["rql:lock:a", "rql:lock:b"]' queue_ttl => 15 acq_id => 'rql:acq:4486/1696/1704/1712/e6fd0da7991e4303' hst_id => 'rql:hst:4486/1696/1712/e6fd0da7991e4303' acs_strat => 'queued' rw_mode => 'write' priority => 0 acq_time => 2.55 (ms)
[redis_queued_locks.lock_series_lock_obtained] lock_key => 'rql:lock:a' lock_keys => '["rql:lock:a", "rql:lock:b"]' queue_ttl => 15 acq_id => 'rql:acq:4486/1696/1704/1712/e6fd0da7991e4303' hst_id => 'rql:hst:4486/1696/1712/e6fd0da7991e4303' acs_strat => 'queued' rw_mode => 'write' priority => 0 acq_time => 2.55 (ms)
[redis_queued_locks.lock_series_obtained] lock_keys => '["rql:lock:a", "rql:lock:b"]' queue_ttl => 15 acq_id => 'rql:acq:4486/1696/1704/1712/e6fd0da7991e4303' hst_id => 'rql:hst:4486/1696/1712/e6fd0da7991e4303' acs_strat => 'queued' rw_mode => 'write' priority => 0 acq_time => 2.55 (ms) reentrant_lock_keys => '[]'
[redis_queued_locks.expire_lock_series] lock_keys => '["rql:lock:a", "rql:lock:b"]' queue_ttl => 15 acq_id => 'rql:acq:4486/1696/1704/1712/e6fd0da7991e4303' hst_id => 'rql:hst:4486/1696/1712/e6fd0da7991e4303' acs_strat => 'queued' rw_mode => 'write' priority => 0#lock_series! - exceptional lock_series
[back to top]
Raises the same errors as #lock! when the series can not be obtained (RedisQueuedLocks::LockAlreadyObtainedError,
RedisQueuedLocks::ConflictLockObtainError, RedisQueuedLocks::LockAcquirementRetryLimitError,
RedisQueuedLocks::LockAcquirementTimeoutError).
For more details see lock_series docs
client.lock_series!("x", "y", "z") { ...some_code... }#lock_info
[back to top]
- get the lock information;
- returns
nilif lock does not exist; - lock data (
Hash<String,String|Integer>):-
"lock_key"-string- lock key in redis; -
"rw_mode"-string- lock mode:"write"(or"read"for read locks info, see Read/Write Locks); -
"acq_id"-string- acquirer identifier (process_id/thread_id/fiber_id/ractor_id/identity); -
"hst_id"-string- host identifier (process_id/thread_id/ractor_id/identity); -
"ts"-numeric/epoch- the time when lock was obtained; -
"ini_ttl"-integer- (milliseconds) initial lock key ttl; -
"rem_ttl"-integer- (milliseconds) remaining lock key ttl; -
<custom metadata>-string/integer- custom metadata passed to thelock/lock!methods viameta:keyword argument (see lock method documentation); - additional keys for reentrant locks and extendable reentrant locks:
- for any type of reentrant locks:
-
"spc_cnt"-integer- how many times the lock was obtained as reentrant lock;
-
- for non-extendable reentrant locks:
-
"l_spc_ts"-numeric/epoch- timestamp of the last non-extendable reentrant lock obtaining;
-
- for extendalbe reentrant locks:
-
"spc_ext_ttl"-integer- (milliseconds) sum of TTL of the each extendable reentrant lock (the total TTL extension time); -
"l_spc_ext_ini_ttl"-integer- (milliseconds) TTL of the last reentrant lock; -
"l_spc_ext_ts"-numeric/epoch- timestamp of the last extendable reentrant lock obtaining;
-
- for any type of reentrant locks:
-
# <without custom metadata>
rql.lock_info("your_lock_name")
# =>
{
"lock_key" => "rql:lock:your_lock_name",
"rw_mode" => "write",
"acq_id" => "rql:acq:123/456/567/678/374dd74324",
"hst_id" => "rql:hst:123/456/678/374dd74324",
"ts" => 123456789.12345,
"ini_ttl" => 5_000,
"rem_ttl" => 4_999
}# <with custom metadata>
rql.lock("your_lock_name", meta: { "kek" => "pek", "bum" => 123 })
rql.lock_info("your_lock_name")
# =>
{
"lock_key" => "rql:lock:your_lock_name",
"rw_mode" => "write",
"acq_id" => "rql:acq:123/456/567/678/374dd74324",
"hst_id" => "rql:hst:123/456/678/374dd74324",
"ts" => 123456789.12345,
"ini_ttl" => 5_000,
"rem_ttl" => 4_999,
"kek" => "pek",
"bum" => "123" # NOTE: returned as a raw string directly from Redis
}# <for reentrant locks>
# (see `conflict_strategy:` kwarg attribute of #lock/#lock! methods and `config['default_conflict_strategy']` config)
rql.lock("your_lock_name", ttl: 5_000)
rql.lock("your_lock_name", ttl: 3_000)
rql.lock("your_lock_name", ttl: 2_000)
rql.lock_info("your_lock_name")
# =>
{
"lock_key" => "rql:lock:your_lock_name",
"rw_mode" => "write",
"acq_id" => "rql:acq:123/456/567/678/374dd74324",
"hst_id" => "rql:hst:123/456/678/374dd74324",
"ts" => 123456789.12345,
"ini_ttl" => 5_000,
"rem_ttl" => 9_444,
# ==> keys for any type of reentrant lock:
"spc_cnt" => 2, # how many times the lock was obtained as reentrant lock
# ==> keys for extendable reentarnt locks with `:extendable_work_through` strategy:
"spc_ext_ttl" => 5_000, # sum of TTL of the each <extendable> reentrant lock (3_000 + 2_000)
"l_spc_ext_ini_ttl" => 2_000, # TTL of the last <extendable> reentrant lock
"l_spc_ext_ts" => 123456792.12345, # timestamp of the last <extendable> reentrant lock obtaining
# ==> keys for non-extendable locks with `:work_through` strategy:
"l_spc_ts" => 123456.789 # timestamp of the last <non-extendable> reentrant lock obtaining
}# <for read/write locks>
# (see `rw_mode:` kwarg attribute of #lock/#lock! methods and "Read/Write Locks" documentation section)
# (lock requests are not included: use #queue_info to see the queued readers and writers)
# -> case 1: the lock is held by readers, writers and readers are waiting in the lock queues;
# process#1 and process#2 (readers, work in parallel):
rql.lock("your_lock_name", rw_mode: :read, ttl: 5_000, meta: { "kek" => "pek" }) { ... }
rql.lock("your_lock_name", rw_mode: :read, ttl: 3_000) { ... }
# process#3 (writer, waits for all readers in the write lock queue):
rql.lock("your_lock_name", rw_mode: :write) { ... }
# process#4 (reader, waits for the earlier writer in the read lock queue):
rql.lock("your_lock_name", rw_mode: :read) { ... }
rql.lock_info("your_lock_name")
# => (read locks info: process#1 and process#2)
{
"lock_key" => "rql:lock:your_lock_name",
"rw_mode" => "read",
"rem_ttl" => 4_985, # remaining ttl of the longest read lock
"readers" => [
{
"acq_id" => "rql:acq:123/456/567/678/374dd74324",
"hst_id" => "rql:hst:123/456/678/374dd74324",
"ts" => 123456789.12345,
"ini_ttl" => 5_000,
"rem_ttl" => 4_985,
"kek" => "pek" # custom metadata of the read lock
},
{
"acq_id" => "rql:acq:124/457/568/679/a83cb4f9d1",
"hst_id" => "rql:hst:124/457/679/a83cb4f9d1",
"ts" => 123456789.54321,
"ini_ttl" => 3_000,
"rem_ttl" => 2_412
}
]
}
# -> case 2: (some time later) readers are released, the lock is held by the writer (process#3),
# the reader (process#4) is still waiting in the read lock queue;
rql.lock_info("your_lock_name")
# => (write lock info: process#3, read lock requests are not included)
{
"lock_key" => "rql:lock:your_lock_name",
"rw_mode" => "write",
"acq_id" => "rql:acq:125/458/569/680/c7bfcaf4f9",
"hst_id" => "rql:hst:125/458/680/c7bfcaf4f9",
"ts" => 123456795.12345,
"ini_ttl" => 5_000,
"rem_ttl" => 4_870
}#queue_info
[back to top]
Returns an information about the required lock queue by the lock name. The result
represnts the ordered lock request queue that is ordered by score (Redis Sets) and shows
lock acquirers and their position in queue. The queue of write lock requests is an empty array
("queue" => []) when only the queue of read lock requests exists.
- get the lock queue information;
- queue represents the ordered set of lock key reqests:
- set is ordered by score in ASC manner (inside the Redis Set);
- score is represented as a timestamp when the lock request was made shifted by the
priority band (
-priority * 2**32seconds: the default priority0keeps the timestamp); - represents the acquirer identifier and their score as an array of hashes;
- returns
nilif lock queues (write and read) do not exist; - lock queue data (
Hash<String,String|Array<Hash<String|Numeric>>):-
"lock_queue"-string- lock queue key in redis (write lock requests); -
"queue"-array- an array of lock requests (array of hashes):-
"acq_id"-string- acquirer identifier (process_id/thread_id/fiber_id/ractor_id/identity by default); -
"score"-float/epoch- the position of the lock request: time when the lock request was made (epoch) shifted by-priority * 2**32seconds (the time itself for the default priority0); -
"rw_mode"-string- the requested lock mode ("write"); -
"priority"-integer- the lock request priority (from-100to100, see Lock Request Prioritization);
-
-
"read_lock_queue","read_queue"- (only when read lock requests exist) the read lock queue key and read lock requests with the same structure ("rw_mode"-"read"), see Read/Write Locks;
-
rql.queue_info("your_lock_name")
# =>
{
"lock_queue" => "rql:lock_queue:your_lock_name",
"queue" => [
# (a lock request of the high priority: ahead of the requests of the default priority)
{ "acq_id" => "rql:acq:123/456/567/678/fa76df9cc2", "score" => -2583360655.459158, "rw_mode" => "write", "priority" => 1 },
{ "acq_id" => "rql:acq:123/567/456/679/c7bfcaf4f9", "score" => 1711606640.540906, "rw_mode" => "write", "priority" => 0 },
{ "acq_id" => "rql:acq:555/329/523/127/7329553b11", "score" => 1711606640.540963, "rw_mode" => "write", "priority" => 0 },
# ...etc
],
# (when read lock requests exist)
"read_lock_queue" => "rql:lock_read_queue:your_lock_name",
"read_queue" => [
{ "acq_id" => "rql:acq:123/456/567/700/fa76df9cc2", "score" => 1711606640.541011, "rw_mode" => "read", "priority" => 0 },
# ...etc
]
}#locked?
[back to top]
- is the lock obtaied or not?
rql.locked?("your_lock_name") # => true/false#queued?
[back to top]
- is the lock queued for obtain / has requests for obtain?
rql.queued?("your_lock_name") # => true/false#unlock - release a lock
[back to top]
- release the concrete lock with lock request queue;
- queue will be relased first;
- (the enabled lock index) the lock name is dropped from the Lock Index in the same transaction;
- has an alias:
#release_lock; - accepts:
-
lock_name- (required)[String]- the lock name that should be released. -
:logger- (optional)[::Logger,#debug]- custom logger object;
- pre-configured in
config['logger'];
-
:instrumenter- (optional)[#notify]- custom instrumenter object;
- pre-configured in
config['instrumetner'];
-
:instrument- (optional)[NilClass,Any];- custom instrumentation data wich will be passed to the instrumenter's payload with :instrument key;
-
nilby default (no additional data);
-
:log_sampling_enabled- (optional)[Boolean]- enables log sampling;
- pre-configured in
config['log_sampling_enabled'];
-
:log_sampling_percent- (optional)[Integer]- log sampling:the percent of cases that should be logged;
- pre-configured in
config['log_sampling_percent'];
-
:log_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Logging::Sampler>]- log sampling: percent-based log sampler that decides should be RQL case logged or not;
- pre-configured in
config['log_sampler'];
-
log_sample_this- (optional)[Boolean]- marks the method that everything should be logged despite the enabled log sampling;
- makes sense when log sampling is enabled;
-
falseby default;
-
:instr_sampling_enabled- (optional)[Boolean]- enables instrumentaion sampling;
- pre-configured in
config['instr_sampling_enabled'];
-
instr_sampling_percent- (optional)[Integer]- the percent of cases that should be instrumented;
- pre-configured in
config['instr_sampling_percent'];
-
instr_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Instrument::Sampler>]- percent-based log sampler that decides should be RQL case instrumented or not;
- pre-configured in
config['instr_sampler'];
-
instr_sample_this- (optional)[Boolean]- marks the method that everything should be instrumneted despite the enabled instrumentation sampling;
- makes sense when instrumentation sampling is enabled;
-
falseby default;
-
- if you try to unlock non-existent lock you will receive
ok: trueresult with operation timings and:nothing_to_releaseresult factor inside;
Return:
-
[Hash<Symbol,Boolean|Hash<Symbol,Numeric|String|Symbol>>]({ ok: true/false, result: Hasn }); -
:resultformat;-
:rel_time-Float- time spent to process redis commands (in milliseconds); -
:rel_key-String- released lock key (RedisQueudLocks-internal lock key name from Redis); -
:rel_queue-String- released lock queue key (RedisQueuedLocks-internal queue key name from Redis); -
:queue_res-Symbol-:released(or:nothing_to_releaseif the required queue does not exist); -
:lock_res-Symbol-:released(or:nothing_to_releaseif the required lock does not exist);
-
Consider that lock_res and queue_res can have different value because of the async nature of invoked Redis'es commands.
rql.unlock("your_lock_name")
# =>
{
ok: true,
result: {
rel_time: 0.02, # time spent to lock release (in milliseconds)
rel_key: "rql:lock:your_lock_name", # released lock key
rel_queue: "rql:lock_queue:your_lock_name", # released lock key queue
queue_res: :released, # or :nothing_to_release
lock_res: :released # or :nothing_to_release
}
}#unlock_read - release the read lock of the current acquirer
[back to top]
- releases the read lock of the current acquirer only (see Read/Write Locks):
other read locks, the write lock and lock requests are not affected (
#unlockreleases the lock entirely); - suitable for read locks obtained without a block of code (
lock(..., rw_mode: :read)without a block); - the current acquirer is calculated in the same way as for
#lock(#current_acquirer_id: process, thread, fiber, ractor, identity), so call it from the same thread/fiber that obtained the read lock; - the read lock of a different acquirer can be released via
:acquirer_id(for example, extracted from#lock_info/#locks_info);:identityis ignored in this case (the acquirer id already contains its own identity); - has an alias:
#release_read_lock; - accepts:
-
lock_name- (required)[String]- the lock name whose read lock should be released; -
:acquirer_id- (optional)[String, NilClass]- the acquirer whose read lock should be released (nilby default: the current acquirer is used); -
:identity- (optional)[String]- the same identity as for#lock(uniq_identityby default); ignored when:acquirer_idis passed: the acquirer id already contains its own identity; -
:logger,:instrumenter,:instrument,:log_sampling_enabled,:log_sampling_percent,:log_sampler,:log_sample_this,:instr_sampling_enabled,:instr_sampling_percent,:instr_sampler,:instr_sample_this- (optional) - the same as for#unlock;
-
- returns
{ ok: true, result: { rel_time:, rel_key:, rel_acq_id:, lock_res: } }(lock_res-:releasedor:nothing_to_release); - raises the
"redis_queued_locks.explicit_read_lock_release"instrumentation event;
rql.lock('report', rw_mode: :read, ttl: 30_000) # => obtained without a block
# ...
rql.unlock_read('report')
# =>
{
ok: true,
result: {
rel_time: 0.32, # milliseconds
rel_key: 'rql:lock:report',
rel_acq_id: 'rql:acq:17580/2260/2380/2280/3f16b93973612580',
lock_res: :released # or :nothing_to_release
}
}# release the read lock of a different acquirer
reader = rql.lock_info('report')['readers'].first
rql.unlock_read('report', acquirer_id: reader['acq_id'])
# =>
{
ok: true,
result: {
rel_time: 0.29, # milliseconds
rel_key: 'rql:lock:report',
rel_acq_id: 'rql:acq:17580/2260/2380/2280/3f16b93973612580', # reader['acq_id']
lock_res: :released # or :nothing_to_release
}
}#clear_locks - release all locks and lock queues
[back to top]
- release all obtained locks and related lock request queues;
- all lock keys (locks, read locks and lock queues) are found in one
SCANpass and deleted during it with oneDELper batch; - (the enabled Lock Index) all locks are found in one
ZSCANpass over the lock index (the keyspace is never scanned): all the keys of each batch of locks (locks, read locks and lock queues) are deleted with oneDELin one transaction with the removal of their lock names from the lock index; keys without the lock index entry (keys of older RQL versions) are not found (see #reindex_locks); - has an alias:
#release_locks; - accepts:
-
:batch_size- (optional)[Integer]- the size of batch of locks and lock queus that should be cleared under the one
DELredis command at once (and theSCANcount); - (the enabled lock index) the number of locks (lock names) whose keys should be cleared under the one
DELredis command at once (and theZSCANcount); - pre-configured in
config['lock_release_batch_size'];
- the size of batch of locks and lock queus that should be cleared under the one
-
:logger- (optional)[::Logger,#debug]- custom logger object;
- pre-configured value in
config['logger'];
-
:instrumenter- (optional)[#notify]- custom instrumenter object;
- pre-configured value in
config['instrumenter'];
-
:instrument- (optional)[NilClass,Any]- custom instrumentation data wich will be passed to the instrumenter's payload with
:instrumentkey;
- custom instrumentation data wich will be passed to the instrumenter's payload with
-
:log_sampling_enabled- (optional)[Boolean]- enables log sampling;
- pre-configured in
config['log_sampling_enabled'];
-
:log_sampling_percent- (optional)[Integer]- log sampling:the percent of cases that should be logged;
- pre-configured in
config['log_sampling_percent'];
-
:log_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Logging::Sampler>]- log sampling: percent-based log sampler that decides should be RQL case logged or not;
- pre-configured in
config['log_sampler'];
-
log_sample_this- (optional)[Boolean]- marks the method that everything should be logged despite the enabled log sampling;
- makes sense when log sampling is enabled;
-
falseby default;
-
:instr_sampling_enabled- (optional)[Boolean]- enables instrumentaion sampling;
- pre-configured in
config['instr_sampling_enabled'];
-
instr_sampling_percent- (optional)[Integer]- the percent of cases that should be instrumented;
- pre-configured in
config['instr_sampling_percent'];
-
instr_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Instrument::Sampler>]- percent-based log sampler that decides should be RQL case instrumented or not;
- pre-configured in
config['instr_sampler'];
-
instr_sample_this- (optional)[Boolean]- marks the method that everything should be instrumneted despite the enabled instrumentation sampling;
- makes sense when instrumentation sampling is enabled;
-
falseby default;
-
- returns:
-
[Hash<Symbol,Numeric>]- Format:{ ok: true, result: Hash<Symbol,Numeric> }; - result data:
-
:rel_time-Numeric- time spent to release all locks and related queus; -
:rel_key_cnt-Integer- the number of released Redis keys (queues+locks);
-
-
rql.clear_locks
# =>
{
ok: true,
result: {
rel_time: 3.07,
rel_key_cnt: 1234
}
}#clear_locks_of
[back to top]
- release all locks of the passed acquirer/host and remove this acquirer/host from all queues (locks will be released first)
- this is a cleanup helper intended for operational and debugging scenarios (for example: your current puma request thread is killed by Rack::Timeout and you need to cleanup all zombie RQL locks and lock reuqests obtained during the request processing);
- acquirer/host dentifiers can be extracted via:
#current_host_id#current_acquirer_id#possible_host_ids- from lock data (extracted via
#lock_info,#locks_info,#queue_info,#queues_info);
- produces
"redis_queued_locks.release_locks_of"instrumentation event; - accepts:
-
:host_id- (required)[String]- host indentifier whose locks we want to release and which we want to remove from all locks queues;
-
:acquirer_id- (required)[String]- acquirer indentifier whose locks we want to release and which we want to remove from all locks queues;
-
:lock_scan_size- (optional)[Integer]- how many items will be released at a time (uses one
SCANpass for batch extraction andDELfor batch deletion); - (the enabled Lock Index) how many locks will be processed at a time (one
ZSCANpass over the lock index for batch extraction andDELfor batch deletion); - pre-configuerd value in
config['clear_locks_of__lock_scan_size'];
- how many items will be released at a time (uses one
-
:queue_scan_size- (optional)[Integer]- how many lock queues will be processed in one round trip (lock queues are found by the same
SCANpass as locks or derived from the lock names of the same lock index pass); - pre-configuerd value in
config['clear_locks_of__queue_scan_size'];
- how many lock queues will be processed in one round trip (lock queues are found by the same
-
:logger- (optional)[::Logger,#debug]- custom logger object;
- pre-configured value in
config['logger'];
-
:instrumenter- (optional)[#notify]- custom instrumenter object;
- pre-configured value in
config['instrumenter'];
-
:instrument- (optional)[NilClass,Any]- custom instrumentation data wich will be passed to the instrumenter's payload with
:instrumentkey;
- custom instrumentation data wich will be passed to the instrumenter's payload with
-
:log_sampling_enabled- (optional)[Boolean]- enables log sampling;
- pre-configured in
config['log_sampling_enabled'];
-
:log_sampling_percent- (optional)[Integer]- log sampling:the percent of cases that should be logged;
- pre-configured in
config['log_sampling_percent'];
-
:log_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Logging::Sampler>]- log sampling: percent-based log sampler that decides should be RQL case logged or not;
- pre-configured in
config['log_sampler'];
-
log_sample_this- (optional)[Boolean]- marks the method that everything should be logged despite the enabled log sampling;
- makes sense when log sampling is enabled;
-
falseby default;
-
:instr_sampling_enabled- (optional)[Boolean]- enables instrumentaion sampling;
- pre-configured in
config['instr_sampling_enabled'];
-
instr_sampling_percent- (optional)[Integer]- the percent of cases that should be instrumented;
- pre-configured in
config['instr_sampling_percent'];
-
instr_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Instrument::Sampler>]- percent-based log sampler that decides should be RQL case instrumented or not;
- pre-configured in
config['instr_sampler'];
-
instr_sample_this- (optional)[Boolean]- marks the method that everything should be instrumneted despite the enabled instrumentation sampling;
- makes sense when instrumentation sampling is enabled;
-
falseby default;
-
- returns:
-
[Hash<Symbol,Numeric>]- Format:{ ok: true, result: Hash<Symbol,Numeric> }; - result data:
-
:rel_time-Numeric- time spent; -
:rel_key_cnt-Integer- the count of released locks; -
:tch_queue_cnt-Integer- the count of touched (modified) queues (the number of queues from which the acquirer/host was removed);
-
-
rql.clear_locks_of(
host_id: "rql:hst:41478/4320/4360/848818f09d8c3420",
acquirer_id: "rql:acq:41478/4320/4340/4360/848818f09d8c3420"
)
# -- or (alias) --
rql.release_locks_of(
host_id: "rql:hst:41478/4320/4360/848818f09d8c3420",
acquirer_id: "rql:acq:41478/4320/4340/4360/848818f09d8c3420"
)
# -> result
{
ok: true,
result: {
rel_key_cnt: 123,
tch_queue_cnt: 2,
rel_time: 0.1
}
}# clear locks and queues of the current acquirer:
rql.clear_locks_of(
host_id: rql.current_host_id,
acquirer_id: rql.current_acquirer_id
)
# equivalent:
rql.clear_current_locks
# -> result
{
ok: true,
result: {
rel_key_cnt: 43,
tch_queue_cnt: 3,
rel_time: 0.2
}
}#clear_current_locks
[back to top]
- release all locks of the current acquirer/host and remove the current acquirer/host from all queues (locks will be released first);
- this is a cleanup helper intended for operational and debugging scenarios (for example: your current puma request thread is killed by Rack::Timeout and you need to cleanup all zombie RQL locks and lock reuqests obtained during the request processing);
- representes an equivalent invocation:
rql.clear_locks_of(host_id: rql.current_host_id, acquirer_id: rql.current_acquirer_id)
- produces
"redis_queued_locks.release_locks_of"instrumentation event;-
:lock_scan_size- (optional)[Integer]- how many items will be released at a time (uses one
SCANpass for batch extraction andDELfor batch deletion); - (the enabled Lock Index) how many locks will be processed at a time (one
ZSCANpass over the lock index for batch extraction andDELfor batch deletion); - pre-configuerd value in
config['clear_locks_of__lock_scan_size'];
- how many items will be released at a time (uses one
-
:queue_scan_size- (optional)[Integer]- how many lock queues will be processed in one round trip (lock queues are found by the same
SCANpass as locks or derived from the lock names of the same lock index pass); - pre-configuerd value in
config['clear_locks_of__queue_scan_size'];
- how many lock queues will be processed in one round trip (lock queues are found by the same
-
:logger- (optional)[::Logger,#debug]- custom logger object;
- pre-configured value in
config['logger'];
-
:instrumenter- (optional)[#notify]- custom instrumenter object;
- pre-configured value in
config['instrumenter'];
-
:instrument- (optional)[NilClass,Any]- custom instrumentation data wich will be passed to the instrumenter's payload with
:instrumentkey;
- custom instrumentation data wich will be passed to the instrumenter's payload with
-
:log_sampling_enabled- (optional)[Boolean]- enables log sampling;
- pre-configured in
config['log_sampling_enabled'];
-
:log_sampling_percent- (optional)[Integer]- log sampling:the percent of cases that should be logged;
- pre-configured in
config['log_sampling_percent'];
-
:log_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Logging::Sampler>]- log sampling: percent-based log sampler that decides should be RQL case logged or not;
- pre-configured in
config['log_sampler'];
-
log_sample_this- (optional)[Boolean]- marks the method that everything should be logged despite the enabled log sampling;
- makes sense when log sampling is enabled;
-
falseby default;
-
:instr_sampling_enabled- (optional)[Boolean]- enables instrumentaion sampling;
- pre-configured in
config['instr_sampling_enabled'];
-
instr_sampling_percent- (optional)[Integer]- the percent of cases that should be instrumented;
- pre-configured in
config['instr_sampling_percent'];
-
instr_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Instrument::Sampler>]- percent-based log sampler that decides should be RQL case instrumented or not;
- pre-configured in
config['instr_sampler'];
-
instr_sample_this- (optional)[Boolean]- marks the method that everything should be instrumneted despite the enabled instrumentation sampling;
- makes sense when instrumentation sampling is enabled;
-
falseby default;
-
- returns:
-
[Hash<Symbol,Numeric>]- Format:{ ok: true, result: Hash<Symbol,Numeric> }; - result data:
-
:rel_time-Numeric- time spent; -
:rel_key_cnt-Integer- the count of released locks; -
:tch_queue_cnt-Integer- the count of touched (modified) queues (the number of queues from which the acquirer/host was removed);
-
-
rql.clear_current_locks
# -- or (alias) --
rql.release_current_locks
# equivalent:
rql.release_locks_of(host_id: rql.current_host_id, acquirer_id: rql.current_acquirer_id)
# -> result
{
ok: true,
result: {
rel_key_cnt: 43,
tch_queue_cnt: 3,
rel_time: 0.2
}
}#extend_lock_ttl
[back to top]
- extends lock ttl by the required number of milliseconds;
- expects the lock name and the number of milliseconds;
- (the enabled lock index) the lock index score of the lock is increased by the same number of milliseconds (see Lock Index);
- accepts:
-
lock_name- (required)[String]- the lock name which ttl should be extended;
-
milliseconds- (required)[Integer]- how many milliseconds should be added to the lock's TTL;
- should be a positive
Integer;
-
:rw_mode- (optional)[Symbol]-
:write(default) - extends the write lock (the behavior described below); -
:read- extends the read lock of the current acquirer only (see Read/Write Locks):- the read lock expiration, the read locks registry TTL and the read lock data TTL are extended;
- an expired read lock (or a read lock replaced by a writer) is never extended ("revived"):
{ ok: false, result: :async_expire_or_no_lock }is returned; - the extension is atomic (it is checked and applied inside a transaction that watches the write lock);
-
-
:all_read_locks- (optional)[Boolean]-
falseby default; -
:readmode only (ignored in:writemode):trueextends all live read locks of the lock (of all acquirers) instead of the read lock of the current acquirer:- each live read lock (its expiration and its data TTL) is extended by
milliseconds, the read locks registry TTL is extended to the longest read lock; - expired read locks are not extended ("revived"); nothing is extended while the write lock is held;
- read locks obtained concurrently with the extension (after it reads the read locks) are not extended;
- returns
{ ok: true, result: { extended_locks_count: <the number of extended read locks> } }when at least one read lock is extended;
- each live read lock (its expiration and its data TTL) is extended by
-
-
:identity- (optional)[String]- the same identity as for
#lock(uniq_identityby default); used for the current acquirer calculation in:readmode;
- the same identity as for
-
:instrumenter- (optional)[#notify]- custom instrumenter object;
- pre-configured in
config['instrumetner'];
-
:instrument- (optional)[NilClass,Any];- custom instrumentation data wich will be passed to the instrumenter's payload with :instrument key;
-
nilby default (no additional data);
-
:logger- (optional)[::Logger,#debug]- custom logger object;
- pre-configured in
config['logger'];
-
:log_sampling_enabled- (optional)[Boolean]- enables log sampling;
- pre-configured in
config['log_sampling_enabled'];
-
:log_sampling_percent- (optional)[Integer]- log sampling:the percent of cases that should be logged;
- pre-configured in
config['log_sampling_percent'];
-
:log_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Logging::Sampler>]- log sampling: percent-based log sampler that decides should be RQL case logged or not;
- pre-configured in
config['log_sampler'];
-
log_sample_this- (optional)[Boolean]- marks the method that everything should be logged despite the enabled log sampling;
- makes sense when log sampling is enabled;
-
falseby default;
-
:instr_sampling_enabled- (optional)[Boolean]- enables instrumentaion sampling;
- pre-configured in
config['instr_sampling_enabled'];
-
instr_sampling_percent- (optional)[Integer]- the percent of cases that should be instrumented;
- pre-configured in
config['instr_sampling_percent'];
-
instr_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Instrument::Sampler>]- percent-based log sampler that decides should be RQL case instrumented or not;
- pre-configured in
config['instr_sampler'];
-
instr_sample_this- (optional)[Boolean]- marks the method that everything should be instrumneted despite the enabled instrumentation sampling;
- makes sense when instrumentation sampling is enabled;
-
falseby default;
-
- returns
{ ok: true, result: { extended_locks_count: Integer } }when ttl is extended:-
extended_locks_count- the number of locks whose TTL is extended:1for the write lock and for the read lock of the current acquirer, the number of extended read locks forall_read_locks: true;
-
- returns
{ ok: false, result: :async_expire_or_no_lock }when a lock not found or a lock is already expired during some steps of invocation (see Important section below); -
Important (
:writemode):- the write lock TTL is extended atomically by one Lua script (
PTTL+PEXPIREwith "current pttl + additional milliseconds"); - the lock owner is not checked: the current write lock is extended, so when your lock is expired and newly obtained by another acquirer, the lock of that acquirer is extended;
- use it at your own risk and consider the async nature when calling this method;
- the write lock TTL is extended atomically by one Lua script (
rql.extend_lock_ttl("my_lock", 5_000) # NOTE: add 5_000 milliseconds
# => `ok` case
{ ok: true, result: { extended_locks_count: 1 } }
# => `failed` case
{ ok: false, result: :async_expire_or_no_lock }#locks - get list of obtained locks
[back to top]
- get list of obtained locks;
- uses redis
SCANunder the hood; - (the enabled Lock Index) uses the lock index under the hood (one
ZSCANpass, the keyspace is never scanned): keys without the lock index entry (keys of older RQL versions) are not found (see #reindex_locks); - accepts:
-
:scan_size-Integer- (config['key_extraction_batch_size']by default) - theSCANcount (or theZSCANcount and the batch size of locks with the enabled lock index); -
:with_info-Boolean-falseby default (for details see #locks_info);
-
- returns:
-
Set<String>(forwith_info: false); -
Set<Hash<Symbol,Any>>(forwith_info: true). See #locks_info for details;
-
rql.locks # or rql.locks(scan_size: 123)
=>
#<Set:
{"rql:lock:locklock75",
"rql:lock:locklock9",
"rql:lock:locklock108",
"rql:lock:locklock7",
"rql:lock:locklock48",
"rql:lock:locklock104",
"rql:lock:locklock13",
"rql:lock:locklock62",
"rql:lock:locklock80",
"rql:lock:locklock28",
...}>#queues - get list of lock request queues
[back to top]
- get list of lock request queues;
- uses redis
SCANunder the hood; - (the enabled Lock Index) uses the lock index under the hood (one
ZSCANpass, the keyspace is never scanned): keys without the lock index entry (keys of older RQL versions) are not found (see #reindex_locks); - accepts
-
:scan_size-Integer- (config['key_extraction_batch_size']by default) - theSCANcount (or theZSCANcount and the batch size of locks with the enabled lock index); -
:with_info-Boolean-falseby default (for details see #queues_info);
-
- returns:
-
Set<String>(forwith_info: false); -
Set<Hash<Symbol,Any>>(forwith_info: true). See #locks_info for details;
-
rql.queues # or rql.queues(scan_size: 123)
=>
#<Set:
{"rql:lock_queue:locklock75",
"rql:lock_queue:locklock9",
"rql:lock_queue:locklock108",
"rql:lock_queue:locklock7",
"rql:lock_queue:locklock48",
"rql:lock_queue:locklock104",
"rql:lock_queue:locklock13",
"rql:lock_queue:locklock62",
"rql:lock_queue:locklock80",
"rql:lock_queue:locklock28",
...}>#keys - get list of taken locks and queues
[back to top]
- get list of taken locks and queues (all the existing keys of the locks: locks, lock queues, read locks registries, read lock queues, read lock data);
- uses redis
SCANunder the hood (allrql:lock*keys); - (the enabled Lock Index) uses the lock index under the hood (one
ZSCANpass, the keyspace is never scanned): keys without the lock index entry (keys of older RQL versions) and otherrql:lock*keys are not listed (see #reindex_locks); - accepts:
:scan_size-Integer- (config['key_extraction_batch_size']by default) - theSCANcount (or theZSCANcount and the batch size of locks with the enabled lock index); - returns:
Set<String>
rql.keys # or rql.keys(scan_size: 123)
=>
#<Set:
{"rql:lock_queue:locklock75",
"rql:lock_queue:locklock9",
"rql:lock:locklock9",
"rql:lock_queue:locklock108",
"rql:lock_queue:locklock7",
"rql:lock:locklock7",
"rql:lock_queue:locklock48",
"rql:lock_queue:locklock104",
"rql:lock:locklock104",
"rql:lock_queue:locklock13",
"rql:lock_queue:locklock62",
"rql:lock_queue:locklock80",
"rql:lock:locklock80",
"rql:lock_queue:locklock28",
...}>#locks_info - get list of locks with their info
[back to top]
- get list of locks with their info;
- uses redis
SCANunder the hod (one pass) or the Lock Index (oneZSCANpass, the keyspace is never scanned: the enabled lock index), lock info is extracted in batches ofscan_sizelocks (two round trips per batch); - accepts
scan_size:/Integeroption (config['key_extraction_batch_size']by default); - returns
Set<Hash<Symbol,Any>>(see #lock_info and examples below for details).- contained data:
{ lock: String, status: Symbol, info: Hash<String,Any> }; -
:lock-String- lock key in Redis; -
:status-Symbol-:releasedor:alive- the lock may become relased durign the lock info extraction process;
-
:infofor:releasedkeys is empty ({});
-
:info-Hash<String,Any>- lock data stored in the lock key in Redis;
- See #lock_info for details;
- contained data:
rql.locks_info # or rql.locks_info(scan_size: 123)
# =>
=> #<Set:
{{:lock=>"rql:lock:some-lock-123",
:status=>:alive,
:info=>{
"acq_id"=>"rql:acq:41478/4320/4340/4360/848818f09d8c3420",
"hst_id"=>"rql:hst:41478/4320/4360/848818f09d8c3420",
"ts"=>1711607112.670343,
"ini_ttl"=>15000,
"lock_key"=>"rql:lock:some-lock-123",
"rw_mode"=>"write",
"rem_ttl"=>13998}},
{:lock=>"rql:lock:some-lock-456",
:status=>:released,
:info=>{},
...}>#queues_info - get list of queues with their info
[back to top]
- get list of queues with their info;
- uses redis
SCANunder the hod (one pass) or the Lock Index (oneZSCANpass, the keyspace is never scanned: the enabled lock index), queue info is extracted in batches ofscan_sizequeues (one round trip per batch); - accepts
scan_size:/Integeroption (config['key_extraction_batch_size']by default); - returns
Set<Hash<Symbol,Any>>(see #queue_info and examples below for details).- contained data:
{ queue: String, requests: Array<Hash<String,Any>> } -
:queue-String- lock key queue in Redis; -
:requests-Array<Hash<String,Any>>- lock requests in the que with their acquirer id, score, requested lock mode ("rw_mode"-"write"forrql:lock_queue:*,"read"for read lock queuesrql:lock_read_queue:*) and priority.
- contained data:
rql.queues_info # or rql.qeuues_info(scan_size: 123)
=> #<Set:
{{:queue=>"rql:lock_queue:some-lock-123",
:requests=>
[{"acq_id"=>"rql:acq:38529/4500/4520/4360/66093702f24a3129", "score"=>1711606640.540842, "rw_mode"=>"write", "priority"=>0},
{"acq_id"=>"rql:acq:38529/4580/4600/4360/66093702f24a3129", "score"=>1711606640.540906, "rw_mode"=>"write", "priority"=>0},
{"acq_id"=>"rql:acq:38529/4620/4640/4360/66093702f24a3129", "score"=>1711606640.5409632, "rw_mode"=>"write", "priority"=>0}]},
{:queue=>"rql:lock_read_queue:some-lock-456",
:requests=>
[{"acq_id"=>"rql:acq:38529/4380/4400/4360/66093702f24a3129", "score"=>1711606640.540722, "rw_mode"=>"read", "priority"=>0},
{"acq_id"=>"rql:acq:38529/4420/4440/4360/66093702f24a3129", "score"=>1711606640.5407748, "rw_mode"=>"read", "priority"=>0}]},
...}>#clear_dead_requests
[back to top]
In some cases your lock requests may become "dead". It means that your lock request lives in lock queue in Redis without
any processing. It can happen when your processs that are enqueeud to the lock queue is failed unexpectedly (for some reason)
before the lock acquire moment occurs and when no any other process does not need this lock anymore.
For this case your lock request will be cleared only when another lock request meets it: a lock request of the same
priority (lock acquirement drops the expired requests of its priority) or a :queued lock request
it blocks (the head of the queue, an earlier request of the other read/write mode); the dead requests of other priorities stay
in the queue.
NOTE: with the enabled Lock Index the lock request queue lives as long as its latest lock request (the queue TTL
is refreshed with the request queue_ttl on each lock request), so the queue of dead requests expires by itself (queues of older
RQL versions and queues created with the disabled lock index have no TTL: see #reindex_locks).
In order to help with these dead requests you may periodically call #clear_dead_requests
with corresponding :dead_ttl option, that is pre-configured by default via config['dead_request_ttl'].
Lock queues are found via the redis SCAN (one pass) or via the Lock Index (one ZSCAN pass, the keyspace is
never scanned: the enabled lock index). Each batch of lock queues takes two round trips: the lock requests are read, then the dead
requests of each priority found in the queues are dropped (no second round trip without dead requests).
With by_priority: true the lock requests are not read: only the first lock request of each priority is read (the dead requests
of a priority are found by its first lock request): a batch takes one round trip per priority of its lock queue with the most
priorities + 1 (the dead requests of a priority are dropped in the round trip that reads the next priority), so the transfer does not
depend on the length of the lock queues: use it for long lock queues with few priorities.
:dead_ttl option is required because of it is no any fast and resource-free way to understand which request
is dead now and is it really dead cuz each request queue can host their requests with
a custom queue ttl for each request differently.
Accepts:
-
:dead_ttl- (optional)[Integer]- lock request ttl after which a lock request is considered dead;
- has a preconfigured value in
config['dead_request_ttl'](1 day by default);
-
:scan_size- (optional)[Integer]- the batch of scanned keys for Redis'es SCAN command;
- (the enabled lock index) the
ZSCANcount of the Lock Index pass and the number of locks (both lock queues of each lock) processed in one batch; - has a preconfigured valie in
config['lock_release_batch_size'];
-
:by_priority- (optional)[Boolean]- read only the first lock request of each priority in the lock queues instead of all lock requests: a batch of lock queues takes one round trip per priority of its lock queue with the most priorities + 1 (instead of two round trips), the transfer does not depend on the length of the lock queues (for long lock queues with few priorities);
-
falseby default (all lock requests are read);
-
:logger- (optional)[::Logger,#debug]- custom logger object;
- pre-configured in
config['logger'];
-
:instrumenter- (optional)[#notify]- custom instrumenter object;
- pre-configured in
config['instrumenter'];
-
:instrument- (optional)[NilClass,Any]- custom instrumentation data wich will be passed to the instrumenter's payload with :instrument key;
-
nilby default (no additional data);
-
:log_sampling_enabled- (optional)[Boolean]- enables log sampling;
- pre-configured in
config['log_sampling_enabled'];
-
:log_sampling_percent- (optional)[Integer]- log sampling:the percent of cases that should be logged;
- pre-configured in
config['log_sampling_percent'];
-
:log_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Logging::Sampler>]- log sampling: percent-based log sampler that decides should be RQL case logged or not;
- pre-configured in
config['log_sampler'];
-
log_sample_this- (optional)[Boolean]- marks the method that everything should be logged despite the enabled log sampling;
- makes sense when log sampling is enabled;
-
falseby default;
-
:instr_sampling_enabled- (optional)[Boolean]- enables instrumentaion sampling;
- pre-configured in
config['instr_sampling_enabled'];
-
instr_sampling_percent- (optional)[Integer]- the percent of cases that should be instrumented;
- pre-configured in
config['instr_sampling_percent'];
-
instr_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Instrument::Sampler>]- percent-based log sampler that decides should be RQL case instrumented or not;
- pre-configured in
config['instr_sampler'];
-
instr_sample_this- (optional)[Boolean]- marks the method that everything should be instrumneted despite the enabled instrumentation sampling;
- makes sense when instrumentation sampling is enabled;
-
falseby default;
Returns: { ok: true, result: { processed_queues: Set<String> } } returns the set of processed lock request queues
(write and read lock request queues);
rql.clear_dead_requests(dead_ttl: 60 * 60 * 1000) # 1 hour in milliseconds
# =>
{
ok: true,
result: {
processed_queues: #<Set: {
"rql:lock_queue:some-lock-123",
"rql:lock_queue:some-lock-456",
"rql:lock_read_queue:some-lock-456",
"rql:lock_queue:your-other-lock",
...
}>
}
}
# long lock queues with few priorities: only the first lock request of each priority is read
rql.clear_dead_requests(dead_ttl: 60 * 60 * 1000, by_priority: true)#reindex_locks
[back to top]
- adds the lock keys without the lock index entry (keys of older RQL versions and keys created with the disabled lock index) to the lock index (see Lock Index);
- invoke it once after the lock index is enabled (
config['lock_index_enabled'] = true) on all your processes: with the enabled lock index all lock-iterating operations (the swarm,#locks,#queues,#keys,#clear_locks,#clear_locks_of,#clear_dead_requests, ...) find locks via the lock index only; - works regardless of
config['lock_index_enabled'](it is not needed while the lock index is disabled: the lock index is neither used nor maintained then); - one
SCANpass over the RQL keys (rql:lock*) with pipelined batches (two round trips per batch); - write locks and read locks registries are indexed with their remaining TTL (+ the grace period), lock queues without TTL
(older RQL versions) get the
queue_ttlTTL first; read lock data is not indexed (it is found via the read locks registry); - idempotent: the lock index scores are never decreased (it can be invoked at any time);
- accepts:
-
:scan_size- (optional)[Integer]- the batch of scanned keys for Redis'es SCAN command;
- pre-configured in
config['lock_release_batch_size'];
-
:queue_ttl- (optional)[Integer]- TTL of the lock queues without TTL (in seconds);
- pre-configured in
config['default_queue_ttl'];
-
:lock_index_grace_period- (optional)[Integer]- the lock index grace period (in milliseconds);
- pre-configured in
config['lock_index_grace_period'];
-
:logger- (optional)[::Logger,#debug]- custom logger object;
- pre-configured in
config['logger'];
-
:instrumenter- (optional)[#notify]- custom instrumenter object;
- pre-configured in
config['instrumetner'];
-
:instrument- (optional)[NilClass,Any];- custom instrumentation data wich will be passed to the instrumenter's payload with :instrument key;
-
nilby default (no additional data);
-
:log_sampling_enabled- (optional)[Boolean]- enables log sampling;
- pre-configured in
config['log_sampling_enabled'];
-
:log_sampling_percent- (optional)[Integer]- log sampling:the percent of cases that should be logged;
- pre-configured in
config['log_sampling_percent'];
-
:log_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Logging::Sampler>]- log sampling: percent-based log sampler that decides should be RQL case logged or not;
- pre-configured in
config['log_sampler'];
-
log_sample_this- (optional)[Boolean]- marks the method that everything should be logged despite the enabled log sampling;
- makes sense when log sampling is enabled;
-
falseby default;
-
:instr_sampling_enabled- (optional)[Boolean]- enables instrumentaion sampling;
- pre-configured in
config['instr_sampling_enabled'];
-
instr_sampling_percent- (optional)[Integer]- the percent of cases that should be instrumented;
- pre-configured in
config['instr_sampling_percent'];
-
instr_sampler- (optional)[#sampling_happened?,Module<RedisQueuedLocks::Instrument::Sampler>]- percent-based log sampler that decides should be RQL case instrumented or not;
- pre-configured in
config['instr_sampler'];
-
instr_sample_this- (optional)[Boolean]- marks the method that everything should be instrumneted despite the enabled instrumentation sampling;
- makes sense when instrumentation sampling is enabled;
-
falseby default;
-
- returns
{ ok: true, result: { idx_key_cnt: Integer } }(the number of indexed keys);
rql.reindex_locks
# =>
{ ok: true, result: { idx_key_cnt: 123 } }#current_acquirer_id
[back to top]
- (aliases:
#current_acq_id,#acq_id); - get the current acquirer identifier in RQL notation that you can use for debugging purposes during the lock analyzation;
- acquirer identifier format:
"rql:acq:#{process_id}/#{thread_id}/#{fiber_id}/#{ractor_id}/#{identity}" - because of the moment that
#lock/#lock!gives you a possibility to customizeprocess_id,fiber_id,thread_id,ractor_idandunique identityidentifiers the#current_acquirer_idmethod provides this possibility too;
Accepts:
-
process_id:- (optional)[Integer,Any]-
::Process.pidby default;
-
-
thread_id:- (optional)[Integer,Any];-
::Thread.current.object_idby default;
-
-
fiber_id:- (optional)[Integer,Any];-
::Fiber.current.object_idby default;
-
-
ractor_id:- (optional)[Integer,Any];-
::Ractor.current.object_idby default;
-
-
identity:- (optional)[String,Any];- this value is calculated once during
RedisQueuedLock::Clientinstantiation and stored in@uniq_identity; - this value can be accessed from
RedisQueuedLock::Client#uniq_identity; - Configuration documentation: see
config['uniq_identifier']; - #lock method documentation: see
uniq_identifier;
- this value is calculated once during
rql.current_acquirer_id
# =>
"rql:acq:38529/4500/4520/4360/66093702f24a3129"#current_host_id
[back to top]
- (aliases:
#current_hst_id,#hst_id); - get a current host identifier in RQL notation that you can use for debugging purposes during the lock analyzis;
- the host is a ruby worker (a combination of process/thread/ractor/identity) that is alive and can obtain locks;
- the host is limited to
process/thread/ractor(withoutfiber) combination cuz we have no abilities to extract all fiber objects from the current ruby process when at least one ractor object is defined (ObjectSpace loses abilities to extractFiberandThreadobjects after the any ractor is created) (Threadobjects are analyzed viaThread.listAPI which does not lose their abilites); - host identifier format:
"rql:hst:#{process_id}/#{thread_id}/#{ractor_id}/#{uniq_identity}" - because of the moment that
#lock/#lock!gives you a possibility to customizeprocess_id,fiber_id,thread_id,ractor_idandunique identityidentifiers the#current_host_idmethod provides this possibility too (except thefiber_idcorrespondingly);
Accepts:
-
process_id:- (optional)[Integer,Any]-
::Process.pidby default;
-
-
thread_id:- (optional)[Integer,Any];-
::Thread.current.object_idby default;
-
-
ractor_id:- (optional)[Integer,Any];-
::Ractor.current.object_idby default;
-
-
identity:- (optional)[String];- this value is calculated once during
RedisQueuedLock::Clientinstantiation and stored in@uniq_identity; - this value can be accessed from
RedisQueuedLock::Client#uniq_identity; - Configuration documentation: see
config['uniq_identifier']; - #lock method documentation: see
uniq_identifier;
- this value is calculated once during
rql.current_host_id
# =>
"rql:acq:38529/4500/4360/66093702f24a3129"#possible_host_ids
[back to top]
- return the list (
Array<String>) of possible host identifiers that can be reached from the current ractor; - the host is a ruby worker (a combination of process/thread/ractor/identity) that is alive and can obtain locks;
- the host is limited to
process/thread/ractor(withoutfiber) combination cuz we have no abilities to extract all fiber objects from the current ruby process when at least one ractor object is defined (ObjectSpace loses abilities to extractFiberandThreadobjects after the any ractor is created) (Threadobjects are analyzed viaThread.listAPI which does not lose their abilites); - host identifier format:
"rql:hst:#{process_id}/#{thread_id}/#{ractor_id}/#{uniq_identity}"
Accepts:
-
identity- (optional)[String];- this value is calculated once during
RedisQueuedLock::Clientinstantiation and stored in@uniq_identity; - this value can be accessed from
RedisQueuedLock::Client#uniq_identity; - Configuration documentation: see
config['uniq_identifier']; - #lock method documentation: see
uniq_identifier;
- this value is calculated once during
rql.possible_host_ids
# =>
[
"rql:hst:18814/2300/2280/5ce0c4582fc59c06", # process id / thread id / ractor id / uniq identity
"rql:hst:18814/2320/2280/5ce0c4582fc59c06", # ...
"rql:hst:18814/2340/2280/5ce0c4582fc59c06", # ...
"rql:hst:18814/2360/2280/5ce0c4582fc59c06", # ...
"rql:hst:18814/2380/2280/5ce0c4582fc59c06", # ...
"rql:hst:18814/2400/2280/5ce0c4582fc59c06"
]Swarm Mode and Zombie Locks
[back to top]
Eliminate zombie locks with a swarm.
This documentation section is in progress! (see the changelog and the usage preview for details at this moment)
- zombie locks and zombie lock requests are found in one
SCANpass over the RQL keys (rql:lock*) or, with the enabled Lock Index (config['lock_index_enabled']), in oneZSCANpass over the lock names: the swarm never scans the whole Redis keyspace then (keys of your other applications are never visited); - after enabling the lock index invoke #reindex_locks once (when all your processes use the lock index): locks created without the lock index are not indexed and are not found by the swarm until then;
(work and usage preview (temporary example-based docs))
- How to Swarm
- configuration
- swarm_status
- swarm_info
- swarmize!
- deswarmize!
- probe_hosts
- flush_zobmies
- zombies_info
- zombie_locks
- zombie_hosts
- zombie_acquirers
Work and Usage Preview (temporary example-based docs)
[back to top]
redis_client = RedisClient.config.new_pool # NOTE: provide your own RedisClient instance
clinet = RedisQueuedLocks::Client.new(redis_client) do |config|
# NOTE: auto-swarm your RQL client after initalization (run swarm elements and their supervisor)
config['swarm.auto_swarm'] = false
# NOTE: the periods, the zombie ttl and the scan sizes should be positive Integers
# supervisor configs
config['swarm.supervisor.liveness_probing_period'] = 2 # NOTE: in seconds
# (probe_hosts) host probing configuration
config['swarm.probe_hosts.enabled_for_swarm'] = true # NOTE: run host-probing from or not
config['swarm.probe_hosts.probe_period'] = 2 # NOTE: (in seconds) the period of time when the probing process is triggered
# (probe_hosts) individual redis config
config['swarm.probe_hosts.redis_config.sentinel'] = false # NOTE: individual redis config
config['swarm.probe_hosts.redis_config.pooled'] = false # NOTE: individual redis config
config['swarm.probe_hosts.redis_config.config'] = {} # NOTE: individual redis config
config['swarm.probe_hosts.redis_config.pool_config'] = {} # NOTE: individual redis config
# (flush_zombies) zombie flushing configuration
config['swarm.flush_zombies.enabled_for_swarm'] = true # NOTE: run zombie flushing or not
config['swarm.flush_zombies.zombie_flush_period'] = 10 # NOTE: (in seconds) period of time when the zombie flusher is triggered
config['swarm.flush_zombies.zombie_ttl'] = 15_000 # NOTE: (in milliseconds) when the lock/host/acquirer is considered a zombie
config['swarm.flush_zombies.zombie_lock_scan_size'] = 500 # NOTE: SCAN count (or ZSCAN count with the enabled lock index) and the batch size of locks during zombie flushing
config['swarm.flush_zombies.zombie_queue_scan_size'] = 500 # NOTE: the batch size of lock queues during zombie flushing (one round trip per batch)
# (flush_zombies) individual redis config
config['swarm.flush_zombies.redis_config.sentinel'] = false # NOTE: individual redis config
config['swarm.flush_zombies.redis_config.pooled'] = false # NOTE: individual redis config
config['swarm.flush_zombies.redis_config.config'] = {} # NOTE: individual redis config
config['swarm.flush_zombies.redis_config.pool_config'] = {} # NOTE: individual redis config
end- obtain some long living lock and kill the host process which will lead the lock becoming a zombie:
daiver => ~/Projects/redis_queued_locks master [$]
➜ bin/console
[1] pry(main)> rql = RedisQueuedLocks::Client.new(RedisClient.new);
[2] pry(main)> rql.swarmize!
/Users/daiver/Projects/redis_queued_locks/lib/redis_queued_locks/swarm/flush_zombies.rb:107: warning: Ractor is experimental, and the behavior may change in future versions of Ruby! Also there are many implementation issues.
=> {:ok=>true, :result=>:swarming}
[3] pry(main)> rql.lock('kekpek', ttl: 1111111111)
=> {:ok=>true,
:result=>
{:lock_key=>"rql:lock:kekpek",
:acq_id=>"rql:acq:17580/2260/2380/2280/3f16b93973612580",
:hst_id=>"rql:hst:17580/2260/2280/3f16b93973612580",
:ts=>1720305351.069259,
:ttl=>1111111111,
:process=>:lock_obtaining}}
[4] pry(main)> exit- start another process, fetch the swarm info, see that our last process is a zombie now and their hosted lock is a zombie too:
daiver => ~/Projects/redis_queued_locks master [$] took 27.2s
➜ bin/console
[1] pry(main)> rql = RedisQueuedLocks::Client.new(RedisClient.new);
[2] pry(main)> rql.swarm_info
=> {"rql:hst:17580/2260/2280/3f16b93973612580"=>{:zombie=>true, :last_probe_time=>2024-07-07 01:35:53 12897/262144 +0300, :last_probe_score=>1720305353.0491982},
"rql:hst:17580/2300/2280/3f16b93973612580"=>{:zombie=>true, :last_probe_time=>2024-07-07 01:35:53 211107/4194304 +0300, :last_probe_score=>1720305353.0503318},
"rql:hst:17580/2320/2280/3f16b93973612580"=>{:zombie=>true, :last_probe_time=>2024-07-07 01:35:53 106615/2097152 +0300, :last_probe_score=>1720305353.050838},
"rql:hst:17580/2260/2340/3f16b93973612580"=>{:zombie=>true, :last_probe_time=>2024-07-07 01:35:53 26239/524288 +0300, :last_probe_score=>1720305353.050047},
"rql:hst:17580/2300/2340/3f16b93973612580"=>{:zombie=>true, :last_probe_time=>2024-07-07 01:35:53 106359/2097152 +0300, :last_probe_score=>1720305353.050716},
"rql:hst:17580/2320/2340/3f16b93973612580"=>{:zombie=>true, :last_probe_time=>2024-07-07 01:35:53 213633/4194304 +0300, :last_probe_score=>1720305353.050934},
"rql:hst:17580/2360/2280/3f16b93973612580"=>{:zombie=>true, :last_probe_time=>2024-07-07 01:35:53 214077/4194304 +0300, :last_probe_score=>1720305353.05104},
"rql:hst:17580/2360/2340/3f16b93973612580"=>{:zombie=>true, :last_probe_time=>2024-07-07 01:35:53 214505/4194304 +0300, :last_probe_score=>1720305353.051142},
"rql:hst:17580/2400/2280/3f16b93973612580"=>{:zombie=>true, :last_probe_time=>2024-07-07 01:35:53 53729/1048576 +0300, :last_probe_score=>1720305353.05124},
"rql:hst:17580/2400/2340/3f16b93973612580"=>{:zombie=>true, :last_probe_time=>2024-07-07 01:35:53 3365/65536 +0300, :last_probe_score=>1720305353.0513458}}
[3] pry(main)> rql.swarm_status
=> {:auto_swarm=>false,
:supervisor=>{:running=>false, :state=>"non_initialized", :observable=>"non_initialized"},
:probe_hosts=>{:enabled=>true, :thread=>{:running=>false, :state=>"non_initialized"}, :main_loop=>{:running=>false, :state=>"non_initialized"}},
:flush_zombies=>{:enabled=>true, :ractor=>{:running=>false, :state=>"non_initialized"}, :main_loop=>{:running=>false, :state=>"non_initialized"}}}
[4] pry(main)> rql.zombies_info
=> {:zombie_hosts=>
#<Set:
{"rql:hst:17580/2260/2280/3f16b93973612580",
"rql:hst:17580/2300/2280/3f16b93973612580",
"rql:hst:17580/2320/2280/3f16b93973612580",
"rql:hst:17580/2260/2340/3f16b93973612580",
"rql:hst:17580/2300/2340/3f16b93973612580",
"rql:hst:17580/2320/2340/3f16b93973612580",
"rql:hst:17580/2360/2280/3f16b93973612580",
"rql:hst:17580/2360/2340/3f16b93973612580",
"rql:hst:17580/2400/2280/3f16b93973612580",
"rql:hst:17580/2400/2340/3f16b93973612580"}>,
:zombie_acquirers=>#<Set: {"rql:acq:17580/2260/2380/2280/3f16b93973612580"}>,
:zombie_locks=>#<Set: {"rql:lock:kekpek"}>}
[5] pry(main)> rql.zombie_locks
=> #<Set: {"rql:lock:kekpek"}>
[6] pry(main)> rql.zombie_acquirers
=> #<Set: {"rql:acq:17580/2260/2380/2280/3f16b93973612580"}>
[7] pry(main)> rql.zombie_hosts
=> #<Set:
{"rql:hst:17580/2260/2280/3f16b93973612580",
"rql:hst:17580/2300/2280/3f16b93973612580",
"rql:hst:17580/2320/2280/3f16b93973612580",
"rql:hst:17580/2260/2340/3f16b93973612580",
"rql:hst:17580/2300/2340/3f16b93973612580",
"rql:hst:17580/2320/2340/3f16b93973612580",
"rql:hst:17580/2360/2280/3f16b93973612580",
"rql:hst:17580/2360/2340/3f16b93973612580",
"rql:hst:17580/2400/2280/3f16b93973612580",
"rql:hst:17580/2400/2340/3f16b93973612580"}>- swarmize the new current ruby process that should run the flush zombies element that will drop zombie locks, zombie hosts and their lock requests in a background:
[8] pry(main)> rql.swarmize!
/Users/daiver/Projects/redis_queued_locks/lib/redis_queued_locks/swarm/flush_zombies.rb:107: warning: Ractor is experimental, and the behavior may change in future versions of Ruby! Also there are many implementation issues.
=> {:ok=>true, :result=>:swarming}
[9] pry(main)> rql.swarm_info
=> {"rql:hst:17752/2260/2280/89beef198021f16d"=>{:zombie=>false, :last_probe_time=>2024-07-07 01:36:39 4012577/4194304 +0300, :last_probe_score=>1720305399.956673},
"rql:hst:17752/2300/2280/89beef198021f16d"=>{:zombie=>false, :last_probe_time=>2024-07-07 01:36:39 4015233/4194304 +0300, :last_probe_score=>1720305399.9573061},
"rql:hst:17752/2320/2280/89beef198021f16d"=>{:zombie=>false, :last_probe_time=>2024-07-07 01:36:39 4016755/4194304 +0300, :last_probe_score=>1720305399.957669},
"rql:hst:17752/2260/2340/89beef198021f16d"=>{:zombie=>false, :last_probe_time=>2024-07-07 01:36:39 1003611/1048576 +0300, :last_probe_score=>1720305399.957118},
"rql:hst:17752/2300/2340/89beef198021f16d"=>{:zombie=>false, :last_probe_time=>2024-07-07 01:36:39 2008027/2097152 +0300, :last_probe_score=>1720305399.957502},
"rql:hst:17752/2320/2340/89beef198021f16d"=>{:zombie=>false, :last_probe_time=>2024-07-07 01:36:39 2008715/2097152 +0300, :last_probe_score=>1720305399.95783},
"rql:hst:17752/2360/2280/89beef198021f16d"=>{:zombie=>false, :last_probe_time=>2024-07-07 01:36:39 4018063/4194304 +0300, :last_probe_score=>1720305399.9579809},
"rql:hst:17752/2360/2340/89beef198021f16d"=>{:zombie=>false, :last_probe_time=>2024-07-07 01:36:39 1004673/1048576 +0300, :last_probe_score=>1720305399.9581308}}
[10] pry(main)> rql.swarm_status
=> {:auto_swarm=>false,
:supervisor=>{:running=>true, :state=>"sleep", :observable=>"initialized"},
:probe_hosts=>{:enabled=>true, :thread=>{:running=>true, :state=>"sleep"}, :main_loop=>{:running=>true, :state=>"sleep"}},
:flush_zombies=>{:enabled=>true, :ractor=>{:running=>true, :state=>"running"}, :main_loop=>{:running=>true, :state=>"sleep"}}}
[11] pry(main)> rql.zombies_info
=> {:zombie_hosts=>#<Set: {}>, :zombie_acquirers=>#<Set: {}>, :zombie_locks=>#<Set: {}>}
[12] pry(main)> rql.zombie_acquirers
=> #<Set: {}>
[13] pry(main)> rql.zombie_hosts
=> #<Set: {}>
[14] pry(main)>"rql:swarm:hsts""rql:index:locks"Lock Index
[back to top]
Find locks without scanning the whole Redis keyspace (opt-in:
config['lock_index_enabled'] = true).
Important
Your locks should work either always with the lock index or always without it (the same
config['lock_index_enabled'] value on all your processes that share the Redis database): locks obtained without the lock
index are not indexed and are invisible to the lock-iterating operations of the processes with the enabled lock index
(the swarm, #locks, #queues, #keys, #clear_locks, ...). So every time you enable the lock index after working without it
(including the upgrade from older RQL versions) invoke #reindex_locks once all your processes use the lock index.
-
disabled by default: lock-iterating operations scan the Redis keyspace (
SCAN MATCH rql:lock*, the classic way), no lock index commands are sent and lock request queues have no TTL; enable the lock index via config:RedisQueuedLocks::Client.new(redis_client) do |config| config['lock_index_enabled'] = true # (milliseconds) (default: 60_000) # - the lock name stays in the lock index for this period after the expiration of all its keys; # - why: the lock index scores use the client clock, so this margin protects the index from the clock skew # between your hosts and from the network latency (otherwise a live lock can drop out of the index and # the swarm/lock-iterating operations will not see it); # - keep it greater than the maximal clock skew between your hosts plus the network latency; config['lock_index_grace_period'] = 60_000 end
-
the client-wide mode (not a per-call option): the lock acquirement maintains the lock index and all lock-iterating operations read it only when it is enabled; use the same mode on all your processes that share the Redis database (locks of the processes without the lock index are not indexed: lock-iterating operations of the processes with the lock index do not see them); the swarm reads the mode when it is started;
-
the lock index is a sorted set
rql:index:locks: the member is the lock name, the score is the upper bound of the lifetime of all lock keys (write lock, read locks registry, lock request queues):client time (epoch, ms) + key ttl + grace period; -
all lock-iterating operations iterate over the lock index (
ZSCAN) and derive lock keys from the lock names instead of the full keyspaceSCAN: their cost depends on the number of your locks only (not on the size of your Redis database):- the swarm:
#flush_zombies, the zombie flusher,#zombie_locks,#zombie_acquirers,#zombies_info; -
#locks/#locks_info,#queues/#queues_info,#keys,#clear_locks,#clear_locks_of/#clear_current_locks,#clear_dead_requests; - only #reindex_locks scans the keyspace (it adds the keys without the lock index entries to the lock index);
- the swarm:
-
the index is maintained by the lock acquirement itself (no background jobs, no additional Redis round trips):
- each lock request adds the lock name to the index (
ZADD GTwith the queue ttl), sets the lock request queue TTL (the queue lives as long as its latest lock request) and drops the expired lock names from the index (ZREMRANGEBYSCORE): 4 commands in the existing queueing pipeline; - each lock obtaining (write and read) adds the lock name with the lock ttl in the same transaction (1 command);
- each lock extension (
#extend_lock_ttl,:extendable_work_throughreentrant locks) increases the score by the extension; - the lock name is dropped from the index when all its keys are expired and the grace period is over, by
#unlock(in the release transaction) and by#clear_locks(in the transaction that deletes the keys of the lock);
- each lock request adds the lock name to the index (
-
config['lock_index_grace_period'](60_000milliseconds by default) andlock_index_grace_period:option of#lock/#lock!/#lock_series/#lock_series!: the lock name stays in the index for this period after the expiration of all its keys; it should be greater than the maximal client clock skew between your hosts plus the duration of one lock acquirement attempt (network latency) (otherwise a lock can be dropped from the index before its expiration and the swarm will not see it); -
(enabling) locks of older RQL versions and locks created with the disabled lock index have no lock index entries (they are not found by lock-iterating operations till then): enable the lock index on all your processes, then invoke #reindex_locks once;
-
(disabling) lock-iterating operations scan the keyspace again; the lock index key is neither used nor maintained anymore (you can delete it:
DEL rql:index:locks); invoke #reindex_locks again after the next enabling; -
(limitation) the lock index is one Redis key written on each lock request (a "hot" key): fine for a standalone Redis (and Sentinel); Redis Cluster is not supported (RQL transactions use several keys of each lock without hash tags);
Lock Index Performance
[back to top]
- measured on a local Redis with 1 million keys of other applications in the same database and ~1 200 locks (+100 lock queues
for the lock-iterating operations, a zombie host for
#flush_zombies): wall time and Redis CPU time of one call with the keyspaceSCAN(config['lock_index_enabled'] = false) and with the lock index (config['lock_index_enabled'] = true):
| Operation | Keyspace SCAN (wall / Redis CPU) |
Lock index (wall / Redis CPU) | Speedup (wall / Redis CPU) |
|---|---|---|---|
#flush_zombies (the zombie flusher) |
263 ms / 181 ms | 20 ms / 2.4 ms | x13 / x75 |
#locks |
269 ms / 192 ms | 7.7 ms / 1.4 ms | x35 / x137 |
#locks_info |
288 ms / 194 ms | 23 ms / 2.3 ms | x12.5 / x84 |
#queues / #queues_info
|
260-280 ms / 190 ms | 8 ms / 1-2 ms | x32-35 / x95-190 |
#keys |
272 ms / 193 ms | 17 ms / 2.6 ms | x16 / x74 |
#clear_dead_requests |
574 ms / 224 ms | 18 ms / 2.2 ms | x32 / x102 |
#clear_locks_of / #clear_current_locks
|
322 ms / 200 ms | 14 ms / 1.9 ms | x23 / x105 |
#clear_locks |
574 ms / 225 ms | 14 ms / 5.1 ms | x41 / x44 |
- the speedup grows with the number of keys in your Redis database: the keyspace
SCANvisits all keys of the database (keys of your other applications too), the lock index visits the lock names only (the cost depends on the number of your locks and on the lock index size, see Lock Index Size); - the zombie flusher runs in every process with the swarm (every
zombie_flush_period): the saved Redis CPU is multiplied by the number of your processes; - the price is paid by the lock acquirement (it maintains the lock index without new round trips: 4 more commands in
the queueing pipeline and 1 more command in the obtaining transaction): ~10% fewer locks per second in a single-thread
lock {}loop on a local Redis, 280 -> 348 allocations perlock {};
Lock Index Size
[back to top]
- the lock index size is about
<the number of distinct lock names per second> * (max(queue_ttl, ttl) + grace period)(~75seconds of lock names with the default settings:config['default_queue_ttl'](15 seconds) +config['lock_index_grace_period'](60 seconds)); - with very diverse lock names (for example,
order:#{id}) lock-iterating operations (the swarm,#locks,#queues,#keys,#clear_locks, ...) visit the dead lock names of this window too (lock names whose keys are already expired); - if it becomes noticeable, there are two levers:
- reduce
config['lock_index_grace_period'](keep it greater than the maximal client clock skew between your hosts plus the network latency); -
TODO: a cheap existence check of the lock name (
EXISTSof its keys) before reading the lock details in lock-iterating operations;
- reduce
Lock Access Strategies
[back to top]
- this documentation section is in progress;
- (little details for a context of the current implementation and feautres):
- defines the way in which the lock should be obitained;
- by default it is configured to obtain a lock in classic
queuedway: you should wait your position in queue in order to obtain a lock; - can be customized in methods
#lockand#lock!via:access_strategyattribute (see method signatures of #lock and #lock! methods); - supports different strategies:
-
:queued(FIFO): the classic queued behavior (default), your lock will be obitaned if you are first in queue and the required lock is free; the queue is ordered by the lock request priorities (FIFO inside the same priority); -
:random(RANDOM): obtain a lock without checking the positions in the queue (but with checking the limist, retries, timeouts and so on). if lock is free to obtain - it will be obtained; (the priorities of other lock requests are ignored too; the lock request itself is queued at the position of its priority like a:queuedone::queuedlock requests wait for it);
-
- for current implementation detalis check:
- Configuration documentation: see
config['default_access_strategy']config docs; - #lock method documentation: see
access_strategyattribute docs;
- Configuration documentation: see
Lock Request Prioritization
[back to top]
-
priority:attribute of#lock,#lock!,#lock_seriesand#lock_series!(config['default_lock_priority']by default): an Integer from-100(the lowest priority) to100(the highest priority),0- (default) normal priority, or a priority name (Symbol) ofconfig['lock_priorities']; - priority names (
config['lock_priorities'], a priority name => its Integer priority):- default names:
:lowest(-100),:low(-50),:normal(0),:high(50),:highest(100); - name the priorities of your application (keep the default names with
merge; the default value is frozen: assign a new hash); - a name is resolved to its Integer priority on each lock acquirement: the lock request queues,
#queue_info/#queues_info, logs and instrumentation have the Integer priority; an unknown name fails withRedisQueuedLocks::ArgumentError; -
config['default_lock_priority']can be a priority name too: an unknown one fails the configuration withRedisQueuedLocks::ConfigValidationError(checked after the configuration block, the keys can be assigned in any order, and on a directconfig[...] =assignment);
- default names:
-
:queuedaccess strategy (default): the lock request is placed in the lock request queue after all requests of the same or higher priority and before all requests of the lower priority: strict priority between priorities, FIFO inside the same priority (read and write lock requests too, see Read/Write Locks);
# a balance operation goes ahead of the email notifications that are already waiting for the lock
rql.lock("user_#{user.id}", priority: 50) { process_balance }
# a payment goes ahead of the balance operations
rql.lock("user_#{user.id}", priority: 90) { process_payment }
# email notifications wait for all lock requests of higher priorities
rql.lock("user_#{user.id}", priority: -10) { send_email }
# normal priority by default
rql.lock("user_#{user.id}") { update_profile } # priority: 0
# the default priority of the client (for example, in background workers)
rql.configure { |config| config['default_lock_priority'] = -10 }
# priority names: the default ones (:lowest, :low, :normal, :high, :highest) and the names of your application
rql.configure do |config|
config['lock_priorities'] = config['lock_priorities'].merge(payment: 90, balance: 50, email: -10)
end
rql.lock("user_#{user.id}", priority: :payment) { process_payment } # priority: 90
rql.lock("user_#{user.id}", priority: :email) { send_email } # priority: -10
rql.lock("user_#{user.id}", priority: :high) { update_profile } # priority: 50- how it works:
- the position of the lock request in the queue (the score) is the request time shifted by the priority band:
request time - priority * 2**32 seconds(each priority has its own range of positions; the default priority0keeps the request time: the positions of RQL versions without priorities); - every lock request drops dead requests (older than
queue_ttl) of its own priority in both lock queues (in the same round trip as before priorities); dead requests of other priorities that block it (the head of the queue and the earlier request of the other read/write mode: the priority and the request time are decoded from the position) are dropped with all dead requests of their priorities in one more round trip of the same attempt, so a dead request of any priority never blocks the queue and the cost of an attempt does not depend on the number of priorities in use; - dead requests of lower priorities never block: they are dropped by the lock requests of their priority (or lower ones)
and by
#clear_dead_requests(it drops the dead requests of every priority found in the queues); - lock requests at infinite positions (
-inf/+inf: manual writes of the lock queues, RQL never writes them) have the bound priorities (100/-100) in#queue_info/#queues_infoand logs; a request at-infis a dead one (like before priorities): it is dropped when it blocks a lock request and by#clear_dead_requests; a request at+infis behind all requests and is never dropped as a dead one; -
#queue_info/#queues_inforeturn the priority of each lock request ("priority"); the lock acquirement logs and instrumentation events (classic, reentrant and lock series ones) have thepriorityof the lock request, thelog_lock_trylogs also have the priorities of the requests ahead (first_priority_in_queue,ahead_priority,dead_priority;first_priority_in_queue => nilwhen the lock queue has no requests);
- the position of the lock request in the queue (the score) is the request time shifted by the priority band:
- limitations and recommendations:
- the priority orders the waiting lock requests only: the obtained lock is never taken away (no preemption);
- strict priority: a continuous flow of requests of a higher priority can starve the requests of lower priorities (they
reach their
timeout/retry_countlimits): give them longer limits; - the released lock is passed by polling: the next lock request notices the released lock on its next attempt
(
retry_delay): use a shorterretry_delayfor the important logic; - the default
retry_count(3) gives a short waiting time: the priority matters for the requests that wait longer (retry_count: nilwithtimeout); - requests of the same priority made within ~61 µs of each other are ordered by their acquirer ids (the precision of the shifted positions);
- each lock request drops dead requests with its own
queue_ttl(the requests of its priority and the requests that block it): a request that waits longer than the shorterqueue_ttlof such requests is dropped by their attempts and comes back at its old position on its own attempts (its ownqueue_ttlis not reached yet), so the requests behind it with a shorterqueue_ttldon't wait for it: it loses its place (and the advantage of its priority) to them, the lock goes to the request whose attempt finds the lock free first; use the samequeue_ttlfor the lock requests of a lock (a longerqueue_ttldoes not keep a request in the queue); -
:randomaccess strategy: the lock request does not wait for its turn (the order of the queues and the priorities of other requests are ignored), but it is queued at the position of its priority::queuedlock requests wait for it (a:randomrequest of a high priority holds back the waiting:queuedrequests of lower priorities until it obtains the lock or leaves the queue); - dead lock requests are dropped by the lock requests that meet them (the requests of their priority and the requests they
block): the dead requests of the priorities that no lock request uses any more (and the dead requests met only by
:randomlock requests) stay in the queues; they never block (an accepted trade-off of the head-driven cleanup: the cost of an attempt does not depend on the number of priorities); without the Lock Index (its queues expire) and the swarm (it drops the requests of dead processes) call#clear_dead_requestsperiodically (e.g. from a scheduled job) to drop them (by_priority: truefor long lock queues: only the first lock request of each priority is read); - all processes that share locks should use RQL versions with priorities before positive priorities are used (
:high,:highest, any priority above0): older versions drop such lock requests as dead ones (the order is broken; the mutual exclusion is not affected: lock queues never take part in it); the default priority (0) and negative priorities (:low,:lowest) work with older versions too: older versions keep such requests behind their own ones and never drop them as dead ones (the dead ones are dropped by the upgraded processes);
Read/Write Locks
[back to top]
-
rw_mode:attribute of#lockand#lock!:-
:write(default) - exclusive lock (the classic RQL lock): waits for the write lock and for all read locks; -
:read- shared lock: waits for the write lock only (read locks of different acquirers work in parallel);
-
# readers work in parallel
rql.lock('report', rw_mode: :read) { read_report }
# writer waits for all readers (and readers wait for the writer)
rql.lock('report', rw_mode: :write) { rebuild_report }
# write mode is default:
rql.lock('report') { rebuild_report } # rw_mode: :write by default- lock request ordering (
access_strategy):-
:queued(default) - FIFO between modes: read lock request waits for every earlier write lock request, write lock request waits for every earlier read and write lock request (so writers are not starved by a continuous flow of readers and consecutive readers obtain the lock together); with lock request priorities "earlier" means "ahead in the queue": a request of a higher priority is ahead of all requests of lower priorities in both modes (FIFO inside the same priority); -
:random- the order of the lock queues is ignored: any free lock is obtained (a continuous flow of readers can starve writers); the lock request itself is queued like any lock request (:queuedlock requests wait for it);
-
- read locks:
- each read lock has its own
ttland is released (after the block execution) or expired independently of other read locks; -
ttlshould be a positiveInteger; - each read lock has its own data with the same structure as the write lock data: acquirer, host, timestamp,
initial ttl,
:meta(with the same reserved keys) and reentrant lock data (spc_cnt,spc_ext_ttl, ...); the read lock data lives as long as the read lock and is returned by#lock_info/#locks_infofor each reader (acquirer and host are not stored: both are derived from the acquirer id); -
#unlockreleases the lock entirely: the write lock, all read locks (with their data) and all lock requests; -
#unlock_read(aka#release_read_lock) releases the read lock of the current acquirer (suitable for read locks obtained without a block), or the read lock of the acquirer passed viaacquirer_id:; -
#extend_lock_ttl(lock_name, milliseconds, rw_mode: :read)extends the read lock of the current acquirer only;all_read_locks: trueextends all live read locks of the lock;
- each read lock has its own
-
#lock_serieswithrw_mode: :readobtains a series of read locks (the mode is the same for all locks of the series):- read lock series of different acquirers work in parallel, writers wait for them;
- after the block only the read locks of the current acquirer are released;
- reentrant read locks of the series (already obtained by the outer logic of the same acquirer) are not released by the series;
- reentrant locks (the same acquirer, see Deadlocks and Reentrant locks):
- read lock request under the obtained read lock or write lock is processed as a reentrant lock of the obtained lock
in accordance with
conflict_strategy; - write lock request under the obtained read lock (read-to-write lock upgrade) fails with
RedisQueuedLocks::ConflictLockObtainError({ ok: false, result: :conflict_lock_upgrade }) for:work_throughand:extendable_work_through(:dead_lockingfails as usual,:wait_for_lockwaits for the read lock expiration);
- read lock request under the obtained read lock or write lock is processed as a reentrant lock of the obtained lock
in accordance with
- info methods:
-
#locked?- the lock is obtained by a writer or by any reader; -
#queued?- there are write or read lock requests; -
#lock_info- write lock info ('rw_mode' => 'write'), or read locks info when there is no write lock:{ 'lock_key' => 'rql:lock:report', 'rw_mode' => 'read', 'rem_ttl' => 4985, # remaining ttl of the longest read lock (milliseconds) 'readers' => [ { 'acq_id' => 'rql:acq:...', 'hst_id' => 'rql:hst:...', 'ts' => 1791582966.125299, 'ini_ttl' => 5000, 'rem_ttl' => 4985, 'some_meta_key' => 'some_meta_value' # (custom `:meta`) }, { 'acq_id' => 'rql:acq:...', 'hst_id' => 'rql:hst:...', 'ts' => 1791582967.5, 'ini_ttl' => 5000, 'rem_ttl' => 3120 } ] }
-
#queue_info- additional"read_lock_queue"/"read_queue"keys when read lock requests exist; each request of#queue_info/#queues_infohas"rw_mode"("write"/"read"); -
#locks/#locks_info,#queues/#queues_info,#keys- include read locks and read lock queues (#locks_infoinfo has'rw_mode'-'write'or'read');
-
- logs and instrumentation:
rw_modeis added to the lock logs and to the instrumentation payloads (lock series logs and events: the mode of the series), see Logging and Instrumentation Events; - data layout:
-
rql:lock:<lock_name>- write lock (HASH, the classic RQL lock); -
rql:lock_queue:<lock_name>- write lock requests (ZSET, the classic RQL lock queue); -
rql:lock_readers:<lock_name>- read locks (ZSET: acquirer id => read lock expiration time in Redis time, milliseconds); -
rql:lock_read_queue:<lock_name>- read lock requests (ZSET); -
rql:lock_reader:<lock_name>:<acquirer_id>- read lock data (HASH, the same structure as the write lock without acquirer and host ids, read lock ttl);
-
- implementation notes:
- optimistic transactions only (
WATCH/MULTI): readers watch the write lock key, writers watch the write lock key and the read locks key, so readers never invalidate transactions of each other; - lock queues are responsible for the ordering only, mutual exclusion is guaranteed by the lock state check;
- all your processes should use the RQL version with read/write locks before you start to use read locks: write locks of older RQL versions do not check read locks;
- optimistic transactions only (
Lock Auto Extending
[back to top]
Keep the lock alive while your block of code is running.
The lock TTL does two different jobs: it limits how long a crashed process blocks other acquirers (a short TTL is better)
and it has to cover the whole block of code (a long TTL is better). With auto_extend: true the TTL does only the first job: it is a lease
that is extended while the block of code is running. When the process dies the extensions stop and the lock expires by itself.
# the block can run longer than 10 seconds; a crashed process releases the lock in 10 seconds at most
rql.lock('report', ttl: 10_000, auto_extend: true) { long_running_logic }
# auto extension with the time of each extension
rql.lock(
'report',
ttl: 2_000, # the first lease
auto_extend: true,
auto_extend_ttl: 30_000, # each extension: 30 seconds from the moment of the extension
max_hold_time_during_auto_extend: 7_200_000 # the lock of a stuck block of code expires in 2 hours
) { long_running_logic }
# both modes, lock series, bang methods
rql.lock('report', rw_mode: :read, auto_extend: true) { long_running_logic }
rql.lock_series('report', 'stats', auto_extend: true) { long_running_logic }
# manual extension inside the block of code: the block that makes progress moves its hold limit
# (see "Manual Lock Lease extending from the running block of code" below)
rql.lock('report', auto_extend: true, max_hold_time_during_auto_extend: 600_000) do |lease|
batches.each do |batch|
process(batch)
lease.hold_for(120_000) # keep the lock at least two more minutes from now
end
end-
auto_extend- keep the lock alive (config['is_auto_extended_by_default'],falseby default). It has no effect without a block of code; -
auto_extend_ttl- how long the lock lives after each extension (config['default_auto_extend_ttl'],nilby default: the lock'sttl):- it is the time from the moment of the extension, not a sum: a lock of a crashed process lives this time at most, whatever the number of extensions was;
- extensions are made each
auto_extend_ttl / 3; - it is the only knob of the trade-off: a process can stall for 2/3 of this value (see the limits below) and a crash blocks other acquirers for this value;
- the extension never shortens the lock: with a longer
ttlthe first extension comes when it is needed;
-
max_hold_time_during_auto_extend- the protection against blocks of code that never finish: a block that hangs forever (an endless loop, a call without a timeout) or a block abandoned midway (a fiber that is never resumed: itsensurenever runs and the lock is not released). Such a block looks like a running one, and without a limit it holds the lock till the end of the process. It is the limit of the extension (config['default_max_hold_time_during_auto_extend'], 1 hour by default,nilmeans no limit), counted from the start of the successful acquirement attempt: the lock is extended up to this moment exactly and expires by itself. It should not be less thanttl. A block of code that makes progress can move the limit (see the lease of the block of code below);
Important
Configure max_hold_time_during_auto_extend yourself, deliberately, for your logic (per call or in config['default_max_hold_time_during_auto_extend']): nil (no limit) or a period that is longer
than your longest block of code. A block of code that runs longer loses its lock at the limit (a timed block is interrupted) unless it moves the limit
by lease.hold_for, and a stuck block of code with nil holds its lock till the end of the process. The default (1 hour) is only a fallback, not a value for your logic.
What happens:
| Case |
timed: false (default) |
timed: true |
|---|---|---|
| the block of code ends | the lock is released | the lock is released |
| the process crashes | the lock expires in auto_extend_ttl at most |
the same |
max_hold_time_during_auto_extend is reached (or the limit moved by lease.hold_for) |
the lock expires, the block of code continues to work, lock_hold_limit_reached is reported |
RedisQueuedLocks::TimedBlockExceedsMaxHoldTimeError |
the lock is lost (#unlock, the swarm, an expiration while the process was stalled, ...) |
the block of code continues to work, auto_extended_lock_lost is reported |
RedisQueuedLocks::TimedBlockLostLockError (the block is not invoked when the lock is lost before it) |
-
timed: truelimits the block of code bymax_hold_time_during_auto_extendinstead of the lock's TTL; withmax_hold_time_during_auto_extend: nilthe block is limited by the lost lock only; - a lost lock is never revived, and the release after the block of code does not touch the lock of the next owner
(the owner is checked; it is not so without
auto_extend, see #lock); - a failed extension (Redis is not available) is reported (
lock_auto_extension_failed) and is tried again sooner (eachauto_extend_ttl / 9by default,config['lock_keeper.extension_retry_ratio']); - the lock keeper thread is tuned by
config['lock_keeper.*'](the idle timeout, the wake-ups, the retries, the batching of the extensions, the schedule slots, the wait for a fiber interruption; see Configuration): the defaults fit most applications; -
timed: truein a non-blocking fiber (a fiber scheduler task,asyncfor example):Thread#raisereaches the current fiber of the thread only, so the keeper interrupts such a block through its fiber scheduler (Fiber::Scheduler#fiber_interrupt, a Ruby 4.0 hook;async>= 2.25 implements it), the same way as a block of a thread: at the hold limit (moved bylease.hold_fortoo) and when the lock is lost. The scheduler raises the error at the next suspension point of the fiber (IO,sleep, ...): a CPU-bound block without them is interrupted when it yields, like by aTimeout. A scheduler without this hook (or a non-blocking fiber without a scheduler): the hold limit is aTimeoutthatlease.hold_forcan not move, and a lost lock interrupts the block only when the block finds it by itself (lease.hold_for), otherwise it is reported only; - reentrant locks: the lock of a block with
auto_extendis extended while this block is running, nested blocks do not need the option; a nested block withauto_extendkeeps the lock of the outer logic alive while the nested block is running; an extension that changes the lock during a reentrant lock attempt repeats this attempt at once (no delay, no spentretry_count, nofail_fastfailure, thetry_lock.exit__reentrant_lock_is_changedlog withlog_lock_try);
Manual Lock Lease extending from the running block of code
[back to top]
A block of code with a parameter gets its lease (RedisQueuedLocks::LockKeeper::LockLease). A block that makes progress moves the hold limit itself, and a stuck
block stops moving it, so its lock expires at the last limit (a dead man's switch instead of one fixed max_hold_time_during_auto_extend):
rql.lock('report', ttl: 10_000, auto_extend: true, max_hold_time_during_auto_extend: 600_000) do |lease|
batches.each do |batch|
process(batch)
lease.hold_for(120_000) # => { ok: true, result: :extended }: two more minutes from now
end
save_report unless lease.lost?
end-
lease.hold_for(milliseconds)- keep the locks at least this time from now: it is not a sum (calls in a loop do not accumulate it) and the limit never moves back; it can move the limit beyondmax_hold_time_during_auto_extend. The locks are extended at once (one round trip with the connection of yourredis_client), each later extension is stillauto_extend_ttlat most (a crash releases the lock inauto_extend_ttl, whatever the limit is). Results:-
{ ok: true, result: :extended }- the limit is moved, all locks are owned and extended; -
{ ok: false, result: :lock_lost }- a lock is lost (auto_extended_lock_lostis reported, the next calls do not move the limit); atimedblock of code is interrupted right there, in any fiber (RedisQueuedLocks::TimedBlockLostLockError); -
{ ok: false, result: :hold_limit_reached }- too late: the limit is reached and the locks are not extended anymore. Call it before the limit: the last extensions end the lock exactly at the limit; -
{ ok: false, result: :released }- the block of code is completed; -
RedisQueuedLocks::ArgumentErrorfor a value that is not a positive Integer;
-
-
lease.lost?- a lock of the block is lost: a local check without Redis (a loss is found by an extension or byhold_for), sofalsedoes not prove the ownership right now; -
lease.hold_time_left- milliseconds till the hold limit (0when it is reached,nil: no limit); -
timed: true: the block of code is interrupted at the moved limit (the keeper thread interrupts it at the hold limit, it is not aTimeout; a non-blocking fiber whose scheduler has nofiber_interruptkeeps theTimeoutofmax_hold_time_during_auto_extend); - one lease per block of code: a lock series has one lease for all its locks, a nested block with
auto_extendhas its own lease; a block without parameters gets no lease (nothing is allocated for it); - call
hold_forper a unit of progress (a batch), not per item: each call is a round trip. From another thread use it only with a connection pool (the connection of your client is used, like by any method of the client); - each moved lock is reported by
lock_hold_limit_extended;
How it works:
- one background thread per
RedisQueuedLocks::Clientextends the locks of all running blocks of the client (all locks that are due in one pipeline). The thread is started on demand and it stops after a minute without blocks. Blocks withoutauto_extendpay nothing, a block that ends before the first extension sends no extensions to Redis; - the thread looks only at the locks that are due (a schedule by the time of the next extension): its work does not grow with the number of running blocks (tens of thousands of blocks in fibers, for example);
- the thread has its own Redis connection, built from the config of your
redis_client: a plainRedisClientis one connection that can not be shared between threads; -
fork: the thread does not survive and a child process does not extend the locks of the parent process;
Limits. The background thread is a Ruby thread of your process, so it has to wait for the Global VM Lock and for the garbage collector like your code. A lock is kept
while the delay of the thread is less than 2/3 of auto_extend_ttl. The delay is about 110 ms per each CPU-bound Ruby thread of the process
(the time slice of a Ruby thread is 100 ms) plus the longest call that holds the GVL (a C extension, for example Marshal.dump of a huge object) or the longest GC pause. So, the
rule is: auto_extend_ttl >= 1.5 * (0.11s * cpu_bound_threads + the longest GVL-holding call).
auto_extend_ttl |
CPU-bound threads, the lock is kept | CPU-bound threads, the lock is lost |
|---|---|---|
| 1 second | 4 | 8 |
| 2 seconds | 8 | 16 |
| 5 seconds | 16 | 32 |
- threads that wait for I/O do not count;
- the
RUBY_THREAD_TIMESLICEenvironment variable (milliseconds) decreases the delay proportionally: withRUBY_THREAD_TIMESLICE=10a lock withauto_extend_ttlof 1 second is kept next to 32 CPU-bound threads; - use
lock_auto_extendedevent to see how much time is left at the moment of an extension (rem_ttl); - like any lease, it can not protect you from a process that is paused between the check of the lock and the write to your storage;
Without the auto extension: a long ttl (it is the hold limit) and the swarm (it removes the locks of dead processes in about zombie_ttl + zombie_flush_period).
There are no extensions at all, but the swarm has to run in your processes.
Deadlocks and Reentrant locks
[back to top]
- this documentation section is in progress;
- (little details for a context of the current implementation and feautres):
- at this moment we support only reentrant locks: they works via customizable conflict strategy behavior
(
:wait_for_lock(default),:work_through,:extendable_work_through,:dead_locking); - by default behavior (
:wait_for_lock) your lock obtaining process will work in a classic way (limits, retries, etc); -
:work_through,:extendable_work_throughworks with limits too (timeouts, delays, etc), but the decision of "is your lock are obtained or not" is made as you work with reentrant locks (your process continues to use the lock without/with lock's TTL extension accordingly); - for current implementation details check:
- Configuration documentation: see
config['default_conflict_strategy']config docs; - #lock method documentation: see
conflict_strategyattribute docs and the method result data;
- Configuration documentation: see
- at this moment we support only reentrant locks: they works via customizable conflict strategy behavior
(
Logging
[back to top]
-
Logging Configuration
-
each lock log contains
rw_mode- the lock mode ('write'or'read', see Read/Write Locks):- the requested mode in lock obtaining logs, try-lock logs (
try_lock.*) andfail_fast_or_limits_reached_or_deadlock__dequeue; - the held mode in
expire_lockanddecrease_lock(the lock that is released or decreased: a reentrant read lock request under the write lock of the same acquirer holds the write lock);
- the requested mode in lock obtaining logs, try-lock logs (
-
default logs (raised from
#lock/#lock!):
"[redis_queued_locks.start_lock_obtaining]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
"[redis_queued_locks.start_try_to_lock_cycle]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
"[redis_queued_locks.dead_score_reached__reset_acquirer_position]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
"[redis_queued_locks.lock_obtained]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
"[redis_queued_locks.lock_obtaining_failed]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time", "result");
"[redis_queued_locks.extendable_reentrant_lock_obtained]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
"[redis_queued_locks.reentrant_lock_obtained]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
"[redis_queued_locks.fail_fast_or_limits_reached_or_deadlock__dequeue]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
"[redis_queued_locks.expire_lock]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
"[redis_queued_locks.decrease_lock]" # (logs "lock_key", "decreased_ttl", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");- additional logs (raised from
#lock/#lock!withconfg[:log_lock_try] == true):
"[redis_queued_locks.try_lock.start]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
"[redis_queued_locks.try_lock.rconn_fetched]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
"[redis_queued_locks.try_lock.same_process_conflict_detected]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
"[redis_queued_locks.try_lock.same_process_conflict_analyzed]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status");
"[redis_queued_locks.try_lock.reentrant_lock__extend_and_work_through]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status", "last_ext_ttl", "last_ext_ts");
"[redis_queued_locks.try_lock.reentrant_lock__work_through]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status", "last_spc_ts");
"[redis_queued_locks.try_lock.single_process_lock_conflict__dead_lock]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status", "last_spc_ts");
"[redis_queued_locks.try_lock.single_process_lock_conflict__lock_upgrade]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status", "last_spc_ts");
"[redis_queued_locks.try_lock.acq_added_to_queue]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
"[redis_queued_locks.try_lock.remove_expired_acqs]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
"[redis_queued_locks.try_lock.dead_request_removed]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "dead_acq_id", "dead_priority");
"[redis_queued_locks.try_lock.get_first_from_queue]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "first_acq_id_in_queue", "first_priority_in_queue");
"[redis_queued_locks.try_lock.exit__queue_ttl_reached]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
"[redis_queued_locks.try_lock.exit__no_first]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "first_acq_id_in_queue", "first_priority_in_queue", "<current_lock_data>");
"[redis_queued_locks.try_lock.exit__lock_still_obtained]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "first_acq_id_in_queue", "first_priority_in_queue", "locked_by_acq_id", "<current_lock_data>");
"[redis_queued_locks.try_lock.exit__write_request_ahead]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "ahead_acq_id", "ahead_priority");
"[redis_queued_locks.try_lock.exit__read_request_ahead]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "ahead_acq_id", "ahead_priority");
"[redis_queued_locks.try_lock.exit__read_lock_still_obtained]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "first_acq_id_in_queue", "first_priority_in_queue");
"[redis_queued_locks.try_lock.exit__reentrant_lock_is_changed]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
"[redis_queued_locks.try_lock.obtain__free_to_acquire]" # (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");- lock series logs (raised from
#lock_series/#lock_series!;rw_modeis the mode of the series; withlog_lock_tryeach attempt of the series writes thetry_lock.*logs of the list above with its ownlock_key, one log per lock of the series):
"[redis_queued_locks.start_lock_series_obtaining]" # (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
"[redis_queued_locks.start_try_to_lock_series_cycle]" # (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
"[redis_queued_locks.dead_score_reached__reset_series_position]" # (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
"[redis_queued_locks.lock_series_intermediate_lock_obtained]" # (logs "lock_key", "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
"[redis_queued_locks.lock_series_lock_obtained]" # (logs "lock_key", "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
"[redis_queued_locks.lock_series_lock_obtaining_failed]" # (logs "lock_key", "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time", "result");
"[redis_queued_locks.lock_series_obtained]" # (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time", "reentrant_lock_keys");
"[redis_queued_locks.lock_series_obtaining_failed]" # (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time", "result", "failed_lock_key");
"[redis_queued_locks.dequeue_from_lock_series_queues]" # (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
"[redis_queued_locks.expire_lock_series]" # (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
"[redis_queued_locks.decrease_lock_series]" # (logs "lock_keys", "decreased_ttl", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");- lock auto extending logs (see Lock Auto Extending; one log per lock;
rw_modeis the mode of the held lock; raised by the lock keeper thread, exceptlock_hold_limit_extended: it is raised from the thread that calledlease.hold_for, as well asauto_extended_lock_lostof a lock thatlease.hold_forfinds lost):
"[redis_queued_locks.lock_auto_extended]" # (logs "lock_key", "rw_mode", "ext_ttl", "rem_ttl", "acq_id", "hst_id");
"[redis_queued_locks.lock_auto_extension_failed]" # (logs "lock_key", "rw_mode", "ext_ttl", "acq_id", "hst_id", "error");
"[redis_queued_locks.auto_extended_lock_lost]" # (logs "lock_key", "rw_mode", "acq_id", "hst_id", "hold_time");
"[redis_queued_locks.lock_hold_limit_reached]" # (logs "lock_key", "rw_mode", "max_hold_time_during_auto_extend", "acq_id", "hst_id");
"[redis_queued_locks.lock_hold_limit_extended]" # (logs "lock_key", "rw_mode", "hold_time", "rem_hold_time", "ext_ttl", "rem_ttl", "acq_id", "hst_id");- operation logs (one log line per operation that changes Redis keys, with the time of the whole operation; the same data as
the instrumentation event of the operation without
instrument):
"[redis_queued_locks.explicit_lock_release]" # (logs "lock_key", "lock_key_queue", "rel_time", "at");
"[redis_queued_locks.explicit_read_lock_release]" # (logs "lock_key", "acq_id", "lock_res", "rel_time", "at");
"[redis_queued_locks.explicit_all_locks_release]" # (logs "at", "rel_time", "rel_key_cnt");
"[redis_queued_locks.release_locks_of]" # (logs "at", "hst_id", "acq_id", "rel_time", "rel_key_cnt", "tch_queue_cnt");
"[redis_queued_locks.extend_lock_ttl]" # (logs "lock_key", "rw_mode", "all_read_locks", "ext_ttl", "extended_locks_count", "ext_time", "at");
"[redis_queued_locks.clear_dead_requests]" # (logs "dead_ttl", "prc_queue_cnt", "rel_time", "at");
"[redis_queued_locks.reindex_locks]" # (logs "idx_key_cnt", "idx_time", "at");- read/write try-lock logs (see Read/Write Locks):
-
single_process_lock_conflict__lock_upgrade- write lock request of the acquirer that holds the read lock (read-to-write lock upgrade is not supported for:work_throughand:extendable_work_throughconflict strategies); -
exit__write_request_ahead- read lock request waits for an earlier write lock request (ahead_acq_id,:queuedaccess strategy); -
exit__read_request_ahead- write lock request waits for an earlier read lock request (ahead_acq_id,:queuedaccess strategy); -
exit__read_lock_still_obtained- write lock request waits for live read locks (read lock request: waits for the own read lock with:wait_for_lockconflict strategy);
-
Logging Configuration
[back to top]
NOTICE: logging can be sampled via:
-
config['log_sampling_enabled'] = true(false by default); -
config['log_sampler'] = RedisQueuedLocks::Logging::Sampler(used by default); - see RedisQueuedLocks::Logging::Sampler implementation in source code for customization details;
# (default: RedisQueuedLocks::Logging::VoidLogger)
# - the logger object;
# - should implement `debug(progname = nil, &block)` (minimal requirement) or be an instance of Ruby's `::Logger` class/subclass;
# - supports `SemanticLogger::Logger` (see "semantic_logger" gem)
# - at this moment the only debug logs are realised in following cases:
# - "[redis_queued_locks.start_lock_obtaining]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.start_try_to_lock_cycle]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.dead_score_reached__reset_acquirer_position]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.lock_obtained]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
# - "[redis_queued_locks.lock_obtaining_failed]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time", "result");
# - "[redis_queued_locks.extendable_reentrant_lock_obtained]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
# - "[redis_queued_locks.reentrant_lock_obtained]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
# - "[redis_queued_locks.fail_fast_or_limits_reached_or_deadlock__dequeue]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.expire_lock]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.decrease_lock]" (logs "lock_key", "decreased_ttl", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.start_lock_series_obtaining]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.start_try_to_lock_series_cycle]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.dead_score_reached__reset_series_position]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.lock_series_intermediate_lock_obtained]" (logs "lock_key", "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
# - "[redis_queued_locks.lock_series_lock_obtained]" (logs "lock_key", "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time");
# - "[redis_queued_locks.lock_series_lock_obtaining_failed]" (logs "lock_key", "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time", "result");
# - "[redis_queued_locks.lock_series_obtained]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time", "reentrant_lock_keys");
# - "[redis_queued_locks.lock_series_obtaining_failed]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority", "acq_time", "result", "failed_lock_key");
# - "[redis_queued_locks.dequeue_from_lock_series_queues]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.expire_lock_series]" (logs "lock_keys", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.decrease_lock_series]" (logs "lock_keys", "decreased_ttl", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.lock_auto_extended]" (logs "lock_key", "rw_mode", "ext_ttl", "rem_ttl", "acq_id", "hst_id");
# - "[redis_queued_locks.lock_auto_extension_failed]" (logs "lock_key", "rw_mode", "ext_ttl", "acq_id", "hst_id", "error");
# - "[redis_queued_locks.auto_extended_lock_lost]" (logs "lock_key", "rw_mode", "acq_id", "hst_id", "hold_time");
# - "[redis_queued_locks.lock_hold_limit_reached]" (logs "lock_key", "rw_mode", "max_hold_time_during_auto_extend", "acq_id", "hst_id");
# - "[redis_queued_locks.lock_hold_limit_extended]" (logs "lock_key", "rw_mode", "hold_time", "rem_hold_time", "ext_ttl", "rem_ttl", "acq_id", "hst_id");
# - "[redis_queued_locks.explicit_lock_release]" (logs "lock_key", "lock_key_queue", "rel_time", "at");
# - "[redis_queued_locks.explicit_read_lock_release]" (logs "lock_key", "acq_id", "lock_res", "rel_time", "at");
# - "[redis_queued_locks.explicit_all_locks_release]" (logs "at", "rel_time", "rel_key_cnt");
# - "[redis_queued_locks.release_locks_of]" (logs "at", "hst_id", "acq_id", "rel_time", "rel_key_cnt", "tch_queue_cnt");
# - "[redis_queued_locks.extend_lock_ttl]" (logs "lock_key", "rw_mode", "all_read_locks", "ext_ttl", "extended_locks_count", "ext_time", "at");
# - "[redis_queued_locks.clear_dead_requests]" (logs "dead_ttl", "prc_queue_cnt", "rel_time", "at");
# - "[redis_queued_locks.reindex_locks]" (logs "idx_key_cnt", "idx_time", "at");
# - "rw_mode" is the requested lock mode ('write'/'read'), the held lock mode for "expire_lock" and "decrease_lock",
# the mode of the series for lock series logs;
# - by default uses VoidLogger that does nothing;
config['logger'] = RedisQueuedLocks::Logging::VoidLogger
# (default: false)
# - adds additional debug logs;
# - enables additional logs for each internal try-retry lock acquiring (a lot of logs can be generated depending on your retry configurations);
# - it adds following debug logs in addition to the existing:
# - "[redis_queued_locks.try_lock.start]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.try_lock.rconn_fetched]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.try_lock.same_process_conflict_detected]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.try_lock.same_process_conflict_analyzed]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status");
# - "[redis_queued_locks.try_lock.reentrant_lock__extend_and_work_through]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status", "last_ext_ttl", "last_ext_ts");
# - "[redis_queued_locks.try_lock.reentrant_lock__work_through]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status", "last_spc_ts");
# - "[redis_queued_locks.try_lock.single_process_lock_conflict__dead_lock]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status", "last_spc_ts");
# - "[redis_queued_locks.try_lock.single_process_lock_conflict__lock_upgrade]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "spc_status", "last_spc_ts");
# - "[redis_queued_locks.try_lock.acq_added_to_queue]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "priority");
# - "[redis_queued_locks.try_lock.remove_expired_acqs]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.try_lock.dead_request_removed]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "dead_acq_id", "dead_priority");
# - "[redis_queued_locks.try_lock.get_first_from_queue]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "first_acq_id_in_queue", "first_priority_in_queue");
# - "[redis_queued_locks.try_lock.exit__queue_ttl_reached]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.try_lock.exit__no_first]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "first_acq_id_in_queue", "first_priority_in_queue", "<current_lock_data>");
# - "[redis_queued_locks.try_lock.exit__lock_still_obtained]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "first_acq_id_in_queue", "first_priority_in_queue", "locked_by_acq_id", "<current_lock_data>");
# - "[redis_queued_locks.try_lock.exit__write_request_ahead]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "ahead_acq_id", "ahead_priority");
# - "[redis_queued_locks.try_lock.exit__read_request_ahead]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "ahead_acq_id", "ahead_priority");
# - "[redis_queued_locks.try_lock.exit__read_lock_still_obtained]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode", "first_acq_id_in_queue", "first_priority_in_queue");
# - "[redis_queued_locks.try_lock.exit__reentrant_lock_is_changed]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "[redis_queued_locks.try_lock.obtain__free_to_acquire]" (logs "lock_key", "queue_ttl", "acq_id", "hst_id", "acs_strat", "rw_mode");
# - "rw_mode" is the requested lock mode ('write'/'read');
config['log_lock_try'] = false
# (default: false)
# - enables <log sampling>: only the configured percent of RQL cases will be logged;
# - disabled by default;
# - works in tandem with <config['log_sampling_percent']> and <config['log_sampler']> configs;
config['log_sampling_enabled'] = false
# (default: 15)
# - the percent of cases that should be logged;
# - take an effect when <config['log_sampling_enabled']> is true;
# - works in tandem with <config['log_sampling_enabled']> and <config['log_sampler']> configs;
config['log_sampling_percent'] = 15
# (default: RedisQueuedLocks::Logging::Sampler)
# - percent-based log sampler that decides should be RQL case logged or not;
# - works in tandem with <config['log_sampling_enabled']> and <config['log_sampling_percent']> configs;
# - based on the ultra simple percent-based (weight-based) algorithm that uses SecureRandom.rand
# method so the algorithm error is ~(0%..13%);
# - you can provide your own log sampler with bettter algorithm that should realize
# `sampling_happened?(percent) => boolean` interface (see `RedisQueuedLocks::Logging::Sampler` for example);
config['log_sampler'] = RedisQueuedLocks::Logging::SamplerInstrumentation
[back to top]
- Instrumentation Events
- Instrumentation Configuration
An instrumentation layer is incapsulated in instrumenter object stored in config (RedisQueuedLocks::Client#config['instrumenter']).
Instrumentation can be sampled. See Instrumentation Configuration section for details.
Instrumenter object should provide notify(event, payload) method with the following signarue:
-
event-string; -
payload-hash<Symbol,Any>;
RQL provides two instrumenters:
-
RedisQueuedLocks::Instrument::ActiveSupport- ActiveSupport::Notifications instrumenter that instrument events via ActiveSupport::Notifications API; -
RedisQueuedLocks::Instrument::VoidNotifier- instrumenter that does nothing;
By default RedisQueuedLocks::Client is configured with the void notifier (which means "instrumentation is disabled").
Instrumentation Configuration
[back to top]
NOTICE: instrumentation can be sampled via:
-
config['instr_sampling_enabled'] = true(false by default); -
config['instr_sampler'] = RedisQueuedLocks::Instrument::Sampler(used by default); - see RedisQueuedLocks::Instrument::Sampler implementation in source code for customization details;
# (default: RedisQueuedLocks::Instrument::VoidNotifier)
# - instrumentation layer;
# - you can provide your own instrumenter that should realize `#notify(event, payload = {})` interface:
# - event: <string> requried;
# - payload: <hash> requried;
# - disabled by default via `VoidNotifier`;
config['instrumenter'] = RedisQueuedLocks::Instrument::ActiveSupport
# (default: false)
# - enables <instrumentaion sampling>: only the configured percent of RQL cases will be instrumented;
# - disabled by default;
# - works in tandem with <config['instr_sampling_percent']> and <config['instr_sampler']>;
config['instr_sampling_enabled'] = false
# (default: 15)
# - the percent of cases that should be instrumented;
# - take an effect when <config['instr_sampling_enabled']> is true;
# - works in tandem with <config['instr_sampling_enabled']> and <config['instr_sampler']> configs;
config['instr_sampling_percent'] = 15
# (default: RedisQueuedLocks::Instrument::Sampler)
# - percent-based log sampler that decides should be RQL case instrumented or not;
# - works in tandem with <config['instr_sampling_enabled']> and <config['instr_sampling_percent']> configs;
# - based on the ultra simple percent-based (weight-based) algorithm that uses SecureRandom.rand
# method so the algorithm error is ~(0%..13%);
# - you can provide your own log sampler with bettter algorithm that should realize
# `sampling_happened?(percent) => boolean` interface (see `RedisQueuedLocks::Instrument::Sampler` for example);
config['instr_sampler'] = RedisQueuedLocks::Instrument::SamplerInstrumentation Events
[back to top]
List of instrumentation events
- "redis_queued_locks.lock_obtained"
- "redis_queued_locks.lock_obtaining_failed"
- "redis_queued_locks.extendable_reentrant_lock_obtained"
- "redis_queued_locks.reentrant_lock_obtained"
- "redis_queued_locks.lock_hold_and_release"
- "redis_queued_locks.reentrant_lock_hold_completes"
- "redis_queued_locks.lock_series_intermediate_lock_obtained"
- "redis_queued_locks.lock_series_lock_obtained"
- "redis_queued_locks.lock_series_lock_obtaining_failed"
- "redis_queued_locks.lock_series_obtained"
- "redis_queued_locks.lock_series_hold_and_release"
- "redis_queued_locks.lock_series_obtaining_failed"
- "redis_queued_locks.lock_auto_extended"
- "redis_queued_locks.lock_auto_extension_failed"
- "redis_queued_locks.auto_extended_lock_lost"
- "redis_queued_locks.lock_hold_limit_reached"
- "redis_queued_locks.lock_hold_limit_extended"
- "redis_queued_locks.explicit_lock_release"
- "redis_queued_locks.explicit_read_lock_release"
- "redis_queued_locks.explicit_all_locks_release"
- "redis_queued_locks.release_locks_of"
- "redis_queued_locks.extend_lock_ttl"
- "redis_queued_locks.clear_dead_requests"
- "redis_queued_locks.reindex_locks"
What is instrumented (each event has a log line with the same name, see Logging, except the release events: lock_hold_and_release,
reentrant_lock_hold_completes and lock_series_hold_and_release are logged as expire_lock/decrease_lock(_series), a :work_through reentrant
lock releases nothing and has no release log):
- the lock acquirement (
#lock/#lock!,#lock_series/#lock_series!): each meaningful outcome (the lock or the whole series is obtained, not obtained, held and released); - the lock auto extending: each extension of each lock and its failures (from the background thread, see Lock Auto Extending);
- each operation that changes Redis keys (
#unlock,#unlock_read,#clear_locks,#clear_locks_of/#clear_current_locks,#extend_lock_ttl,#clear_dead_requests,#reindex_locks): one event with the time of the whole operation; - lock information queries (
#lock_info,#locks,#queues,#keys, ...) are not instrumented; - the swarm (
#probe_hosts,#flush_zombiesand the swarm elements) is not instrumented yet;
Detalized event semantics and payload structure:
"redis_queued_locks.lock_obtained"
- [back to the list]
- a moment when the lock was obtained;
- raised from
#lock/#lock!; - payload:
-
:ttl-integer/milliseconds- lock ttl; -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:lock_key-string- lock name; -
:rw_mode-symbol- requested lock mode::writeor:read(see Read/Write Locks); -
:priority-integer- lock request priority: from-100to100(a priority name is reported as its integer priority, see Lock Request Prioritization); -
:ts-numeric/epoch- the time when the lock was obtaiend; -
:acq_time-float/milliseconds- time spent on lock acquiring; -
:instrument-nil/Any- custom data passed to the#lock/#lock!method as:instrumentattribute;
-
"redis_queued_locks.lock_obtaining_failed"
- [back to the list]
- a moment when the lock acquirement is failed (the lock is not obtained);
- raised from
#lock/#lock!(withraise_errors: true- before the error is raised); - payload:
-
:lock_key-string- lock name; -
:rw_mode-symbol- requested lock mode::writeor:read(see Read/Write Locks); -
:priority-integer- lock request priority: from-100to100(a priority name is reported as its integer priority, see Lock Request Prioritization); -
:ttl-integer/milliseconds- requested lock ttl; -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:ts-numeric/epoch- the time when the lock acquirement is failed; -
:acq_time-float/milliseconds- time spent on lock acquiring; -
:result-symbol- the failure result::timeout_reached,:retry_limit_reached,:fail_fast_no_try,:fail_fast_after_try,:conflict_dead_lock,:conflict_lock_upgrade(see lock); -
:instrument-nil/Any- custom data passed to the#lock/#lock!method as:instrumentattribute;
-
"redis_queued_locks.extendable_reentrant_lock_obtained"
- [back to the list]
- an event signalizes about the "extendable reentrant lock" obtaining is happened;
- raised from
#lock/#lock!when the lock was obtained as reentrant lock; - payload:
-
:lock_key-string- lock name; -
:rw_mode-symbol- requested lock mode::writeor:read(see Read/Write Locks); a read lock request under the write lock of the same acquirer works through the write lock (:rw_modeis:read); -
:priority-integer- requested lock request priority: from-100to100(a priority name is reported as its integer priority; a reentrant lock request is not queued, see Lock Request Prioritization); -
:ttl-integer/milliseconds- last lock ttl by reentrant locking; -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:ts-numeric/epoch- the time when the lock was obtaiend as extendable reentrant lock; -
:acq_time-float/milliseconds- time spent on lock acquiring; -
:instrument-nil/Any- custom data passed to the#lock/#lock!method as:instrumentattribute;
-
"redis_queued_locks.reentrant_lock_obtained"
- [back to the list]
- an event signalizes about the "reentrant lock" obtaining is happened (without TTL extension);
- raised from
#lock/#lock!when the lock was obtained as reentrant lock; - payload:
-
:lock_key-string- lock name; -
:rw_mode-symbol- requested lock mode::writeor:read(see Read/Write Locks); a read lock request under the write lock of the same acquirer works through the write lock (:rw_modeis:read); -
:priority-integer- requested lock request priority: from-100to100(a priority name is reported as its integer priority; a reentrant lock request is not queued, see Lock Request Prioritization); -
:ttl-integer/milliseconds- last lock ttl by reentrant locking; -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:ts-numeric/epoch- the time when the lock was obtaiend as reentrant lock; -
:acq_time-float/milliseconds- time spent on lock acquiring; -
:instrument-nil/Any- custom data passed to the#lock/#lock!method as:instrumentattribute;
-
"redis_queued_locks.lock_hold_and_release"
- [back to the list]
- an event signalizes about the "hold+and+release" process is finished;
- raised from
#lock/#lock!when invoked with a block of code; - payload:
-
:hold_time-float/milliseconds- lock hold time; -
:ttl-integer/milliseconds- lock ttl; -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:lock_key-string- lock name; -
:rw_mode-symbol- requested lock mode::writeor:read(see Read/Write Locks); -
:priority-integer- lock request priority: from-100to100(a priority name is reported as its integer priority, see Lock Request Prioritization); -
:ts-numeric/epoch- the time when lock was obtained; -
:acq_time-float/milliseconds- time spent on lock acquiring; -
:instrument-nil/Any- custom data passed to the#lock/#lock!method as:instrumentattribute;
-
"redis_queued_locks.reentrant_lock_hold_completes"
- [back to the list]
- an event signalizes about the "reentrant lock hold" is complete (both extendable and non-extendable);
- lock re-entering can happen many times and this event happens for each of them separately;
- raised from
#lock/#lock!when the lock was obtained as reentrant lock; - payload:
-
:hold_time-float/milliseconds- lock hold time; -
:ttl-integer/milliseconds- last lock ttl by reentrant locking; -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:ts-numeric/epoch- the time when the lock was obtaiend as reentrant lock; -
:lock_key-string- lock name; -
:rw_mode-symbol- requested lock mode::writeor:read(see Read/Write Locks); a read lock request under the write lock of the same acquirer works through the write lock (:rw_modeis:read); -
:priority-integer- requested lock request priority: from-100to100(a priority name is reported as its integer priority; a reentrant lock request is not queued, see Lock Request Prioritization); -
:acq_time-float/milliseconds- time spent on lock acquiring; -
:instrument-nil/Any- custom data passed to the#lock/#lock!method as:instrumentattribute;
-
"redis_queued_locks.lock_series_intermediate_lock_obtained"
- [back to the list]
- intermediate obtaining: a moment when the lock of the series passed all checks of an attempt of the series (the lock is free and the lock request of the series is next). Nothing is held yet: the series can still wait for its other locks or fail;
- raised from
#lock_series/#lock_series!once per lock of the series (not per attempt), in the order of the lock names up to the lock that blocks the series; reentrant locks of the series are not reported; - payload:
-
:lock_key-string- the lock of the series; -
:lock_keys-array<string>- all locks of the series; -
:rw_mode-symbol- the mode of the series::writeor:read(see Read/Write Locks); -
:priority-integer- the lock request priority of the series (priority): from-100to100(a priority name is reported as its integer priority, see Lock Request Prioritization); -
:ttl-integer/milliseconds- the ttl of each lock of the series; -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:ts-float/epoch- the time of the event; -
:acq_time-float/milliseconds- time spent on the series acquiring up to this moment; -
:instrument-nil/Any- custom data passed to the#lock_series/#lock_series!method as:instrumentattribute;
-
"redis_queued_locks.lock_series_lock_obtained"
- [back to the list]
- full obtaining: a moment when the lock of the series was really obtained (all locks of the series are held);
- raised from
#lock_series/#lock_series!for each lock obtained by the series, right beforelock_series_obtained; reentrant locks of the series are not reported (see:reentrant_lock_keysoflock_series_obtained); - payload:
-
:lock_key-string- the lock of the series; -
:lock_keys-array<string>- all locks of the series; -
:rw_mode-symbol- the mode of the series::writeor:read(see Read/Write Locks); -
:priority-integer- the lock request priority of the series (priority): from-100to100(a priority name is reported as its integer priority, see Lock Request Prioritization); -
:ttl-integer/milliseconds- the ttl of each lock of the series; -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:ts-float/epoch- the time when the series was obtained; -
:acq_time-float/milliseconds- time spent on the series acquiring; -
:instrument-nil/Any- custom data passed to the#lock_series/#lock_series!method as:instrumentattribute;
-
"redis_queued_locks.lock_series_lock_obtaining_failed"
- [back to the list]
- a moment when the series acquirement is failed: the lock of the series that blocked it;
- raised from
#lock_series/#lock_series!once per failed series (withraise_errors: true- before the error is raised), right beforelock_series_obtaining_failed; it is not raised when the blocking lock is unknown (no attempt found it); - payload:
-
:lock_key-string- the lock that blocked the series; -
:lock_keys-array<string>- all locks of the series; -
:rw_mode-symbol- the mode of the series::writeor:read(see Read/Write Locks); -
:priority-integer- the lock request priority of the series (priority): from-100to100(a priority name is reported as its integer priority, see Lock Request Prioritization); -
:ttl-integer/milliseconds- the ttl of each lock of the series; -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:ts-float/epoch- the time when the series acquirement was failed; -
:acq_time-float/milliseconds- time spent on the series acquiring; -
:result-symbol- the failure result (seelock_series_obtaining_failed); -
:instrument-nil/Any- custom data passed to the#lock_series/#lock_series!method as:instrumentattribute;
-
"redis_queued_locks.lock_series_obtained"
- [back to the list]
- a moment when all locks of the series were obtained;
- raised from
#lock_series/#lock_series!; - payload:
-
:lock_keys-array<string>- lock names of the series; -
:rw_mode-symbol- the mode of the series::writeor:read(see Read/Write Locks); -
:priority-integer- the lock request priority of the series (priority): from-100to100(a priority name is reported as its integer priority, see Lock Request Prioritization); -
:ttl-integer/milliseconds- the ttl of each lock of the series (see lock_series); -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:ts-numeric/epoch- the time when the series was obtained; -
:acq_time-float/milliseconds- time spent on the series acquiring; -
:reentrant_lock_keys-array<string>- the locks of the series that are obtained by your outer logic (reentrant locks: they are not obtained and not released by the series); -
:instrument-nil/Any- custom data passed to the#lock_series/#lock_series!method as:instrumentattribute;
-
"redis_queued_locks.lock_series_hold_and_release"
- [back to the list]
- an event signalizes about the "hold+and+release" process of the series is finished;
- raised from
#lock_series/#lock_series!when invoked with a block of code; - payload:
-
:lock_keys-array<string>- lock names of the series; -
:rw_mode-symbol- the mode of the series::writeor:read(see Read/Write Locks); -
:priority-integer- the lock request priority of the series (priority): from-100to100(a priority name is reported as its integer priority, see Lock Request Prioritization); -
:hold_time-float/milliseconds- the series hold time; -
:ttl-integer/milliseconds- the ttl of each lock of the series; -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:ts-float/epoch- the time when the series was released; -
:acq_time-float/milliseconds- time spent on the series acquiring; -
:reentrant_lock_keys-array<string>- the locks of the series that are obtained by your outer logic (reentrant locks: they are not obtained and not released by the series); -
:instrument-nil/Any- custom data passed to the#lock_series/#lock_series!method as:instrumentattribute;
-
"redis_queued_locks.lock_series_obtaining_failed"
- [back to the list]
- a moment when the series acquirement is failed (no lock of the series is obtained);
- raised from
#lock_series/#lock_series!(withraise_errors: true- before the error is raised); - payload:
-
:lock_keys-array<string>- lock names of the series; -
:rw_mode-symbol- the mode of the series::writeor:read(see Read/Write Locks); -
:priority-integer- the lock request priority of the series (priority): from-100to100(a priority name is reported as its integer priority, see Lock Request Prioritization); -
:ttl-integer/milliseconds- the ttl of each lock of the series; -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:ts-float/epoch- the time when the series acquirement was failed; -
:acq_time-float/milliseconds- time spent on the series acquiring; -
:result-symbol- the failure result::timeout_reached,:retry_limit_reached,:fail_fast_no_try,:fail_fast_after_try,:conflict_dead_lock,:conflict_lock_upgrade; -
:failed_lock_key-string/nil- the first lock that blocked the last completed attempt of the series (nil: unknown: no attempt was completed or some lock state was changed during the attempt); -
:instrument-nil/Any- custom data passed to the#lock_series/#lock_series!method as:instrumentattribute;
-
"redis_queued_locks.lock_auto_extended"
- [back to the list]
- an event signalizes about the extended lock (see Lock Auto Extending);
- raised by the lock keeper thread, one event per lock per extension;
- payload:
-
:lock_key-string- lock key (rql:lock:<lock_name>); -
:rw_mode-symbol- the mode of the held lock (:writeor:read); -
:ext_ttl-integer/milliseconds- how long the lock should live after the extension; -
:rem_ttl-integer/milliseconds- how long the lock really lives after the extension (the extension never shortens the lock); -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:at-float/epoch- the time when the event was reported; -
:instrument-nil/Any- custom data passed to the#lock/#lock_seriesmethod as:instrumentattribute;
-
"redis_queued_locks.lock_auto_extension_failed"
- [back to the list]
- an event signalizes about the failed extension (Redis is not available, for example): it is tried again sooner;
- raised by the lock keeper thread, one event per lock per failure;
- payload:
-
:lock_key-string- lock key (rql:lock:<lock_name>); -
:rw_mode-symbol- the mode of the held lock (:writeor:read); -
:ext_ttl-integer/milliseconds- how long the lock should live after the extension; -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:error-string- the class name of the error; -
:at-float/epoch- the time when the event was reported; -
:instrument-nil/Any- custom data passed to the#lock/#lock_seriesmethod as:instrumentattribute;
-
"redis_queued_locks.auto_extended_lock_lost"
- [back to the list]
- an event signalizes that the lock of the running block of code is lost: it is expired or released, or it is obtained by another acquirer;
- raised by the lock keeper thread (or from the thread that called
#hold_for, when#hold_forfinds the lost lock), one event per lock; - payload:
-
:lock_key-string- lock key (rql:lock:<lock_name>); -
:rw_mode-symbol- the mode of the held lock (:writeor:read); -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:hold_time-integer/milliseconds- time from the start of the successful acquirement attempt to the moment when the loss is found; -
:at-float/epoch- the time when the event was reported; -
:instrument-nil/Any- custom data passed to the#lock/#lock_seriesmethod as:instrumentattribute;
-
"redis_queued_locks.lock_hold_limit_reached"
- [back to the list]
- an event signalizes that the block of code reached its hold limit (
max_hold_time_during_auto_extendor the limit moved bylease.hold_for): the lock is not extended anymore; - raised by the lock keeper thread, one event per lock;
- payload:
-
:lock_key-string- lock key (rql:lock:<lock_name>); -
:rw_mode-symbol- the mode of the held lock (:writeor:read); -
:max_hold_time_during_auto_extend-integer/milliseconds- themax_hold_time_during_auto_extendoption of the block of code (the initial limit: it stays the same when the limit is moved bylease.hold_for); -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:at-float/epoch- the time when the event was reported; -
:instrument-nil/Any- custom data passed to the#lock/#lock_seriesmethod as:instrumentattribute;
-
"redis_queued_locks.lock_hold_limit_extended"
- [back to the list]
- an event signalizes that the block of code moved its hold limit and the lock is extended at once (
RedisQueuedLocks::LockKeeper::LockLease#hold_for); - raised from the thread that called
#hold_for, one event per lock (a lost lock is reported byauto_extended_lock_lostinstead); - payload:
-
:lock_key-string- lock key (rql:lock:<lock_name>); -
:rw_mode-symbol- the mode of the held lock (:writeor:read); -
:hold_time-integer/milliseconds- the requested time (from the moment of the call); -
:rem_hold_time-integer/milliseconds/nil- the time left till the hold limit after the call (nil: no limit); -
:ext_ttl-integer/milliseconds- how long the lock should live after the extension (auto_extend_ttl, the hold limit at most); -
:rem_ttl-integer/milliseconds- how long the lock really lives after the extension (the extension never shortens the lock); -
:acq_id-string- lock acquirer identifier; -
:hst_id-string- lock's host identifier; -
:at-float/epoch- the time when the event was reported; -
:instrument-nil/Any- custom data passed to the#lock/#lock_seriesmethod as:instrumentattribute;
-
"redis_queued_locks.explicit_lock_release"
- [back to the list]
- an event signalizes about the explicit lock release (invoked via
RedisQueuedLock#unlock); - raised from
#unlock; - the write lock, all read locks and both lock request queues (write and read) are released;
- payload:
-
:at-float/epoch- the time when the lock was released; -
:rel_time-float/milliseconds- time spent on lock releasing; -
:lock_key-string- released lock (lock name); -
:lock_key_queue-string- released lock queue (the queue of write lock requests); -
:instrument-nil/Any- custom data passed to the#unlockmethod as:instrumentattribute;
-
"redis_queued_locks.explicit_read_lock_release"
- [back to the list]
- an event signalizes about the explicit release of the read lock of the concrete acquirer (invoked via
RedisQueuedLock#unlock_read); - raised from
#unlock_read(aka#release_read_lock); - payload:
-
:at-float/epoch- the time when the read lock was released; -
:rel_time-float/milliseconds- time spent on read lock releasing; -
:lock_key-string- lock key (rql:lock:<lock_name>); -
:acq_id-string- the read lock acquirer; -
:lock_res-symbol-:releasedor:nothing_to_release; -
:instrument-nil/Any- custom data passed to the#unlock_readmethod as:instrumentattribute;
-
"redis_queued_locks.explicit_all_locks_release"
- [back to the list]
- an event signalizes about the explicit all locks release (invoked via
RedisQueuedLock#clear_locks); - raised from
#clear_locks; - payload:
-
:rel_time-float/milliseconds- time spent on "realese all locks" operation; -
:at-float/epoch- the time when the operation has ended; -
:rel_key_cnt-integer- released redis keys count (write locks, readers registries, read lock data, write and read lock request queues); -
:instrument-nil/Any- custom data passed to the#clear_locksmethod as:instrumentattribute;
-
"redis_queued_locks.release_locks_of"
- [back to the list]
- an event signalizes about the released locks (and removement from lock queues) of the concrete host and acquirer;
- raised from
#clear_locks_ofand#clear_current_locks(#release_locks_ofand#release_current_locksrespectively); - payload:
-
:rel_time-float/milliseconds- time spent on "release locks of" operation; -
:at-float/epoch- the time when the opertaion has ended; -
:acq_id-string- refused acquirer identifier; -
:hst_id-string- refused host identifier; -
:rel_key_cnt-integer- released locks count (write locks and read locks); -
:tch_queue_cnt-:integer- the number of queues (write and read lock request queues) from which the concrete host/acquirer was removed; -
:instrument-nil/Any- custom data passed to the#clear_locks_of/#clear_current_locksmethod as:instrumentattribute;
-
"redis_queued_locks.extend_lock_ttl"
- [back to the list]
- an event signalizes about the lock TTL extension (successful or not);
- raised from
#extend_lock_ttl; - payload:
-
:lock_key-string- lock key (rql:lock:<lock_name>); -
:rw_mode-symbol-:write(the write lock) or:read(the read lock of the acquirer or all read locks); -
:all_read_locks-boolean- all read locks of the lock are extended (:readmode); -
:ext_ttl-integer/milliseconds- the extension (millisecondsargument); -
:extended_locks_count-integer- the number of extended locks (0when nothing is extended); -
:ext_time-float/milliseconds- time spent on the extension; -
:at-float/epoch- the time when the operation has ended; -
:instrument-nil/Any- custom data passed to the#extend_lock_ttlmethod as:instrumentattribute;
-
"redis_queued_locks.clear_dead_requests"
- [back to the list]
- an event signalizes about the dropped dead lock requests;
- raised from
#clear_dead_requests; - payload:
-
:dead_ttl-integer/milliseconds- lock requests older thandead_ttlare dropped; -
:prc_queue_cnt-integer- the number of processed lock request queues (write and read); -
:rel_time-float/milliseconds- time spent on the operation; -
:at-float/epoch- the time when the operation has ended; -
:instrument-nil/Any- custom data passed to the#clear_dead_requestsmethod as:instrumentattribute;
-
"redis_queued_locks.reindex_locks"
- [back to the list]
- an event signalizes about the lock keys added to the Lock Index;
- raised from
#reindex_locks; - payload:
-
:idx_key_cnt-integer- the number of indexed keys; -
:idx_time-float/milliseconds- time spent on the operation; -
:at-float/epoch- the time when the operation has ended; -
:instrument-nil/Any- custom data passed to the#reindex_locksmethod as:instrumentattribute;
-
Roadmap
[back to top]
-
Major:
- think about "thread priority" configuration 🤔;
- add
hst_idto all methods that works with queues info; - try to return the
fiber object idto the lock host identifier (we cant use fiber object id cuzObjectSpacehas no access to the fiber object space after the any ractor object initialization) - Swarm:
- circuit-breaker for long-living failures of your infrastructure inside the swarm elements and supervisor:
the supervisor will stop (for some period of time or while the some factor will return
true) trying to ressurect unexpectedly terminated swarm elements, and will notify about this; - swarm logs (thread/ractor has some limitations so the initial implementation does not include swarm logging);
- swarm instrumentation (thread/ractor has some limitations so the initial implementation does not include swarm instrumentation);
- circuit-breaker for long-living failures of your infrastructure inside the swarm elements and supervisor:
the supervisor will stop (for some period of time or while the some factor will return
- isolated timeouts which are independent of internal Ruby's timeout implementation (where all timeouts are hostend inside the global "timeout request" queue and managed by a single global "timeout wathcer" thread). it should prevent any logic and timeout intersections, some GVL-related things and problem situations when the global watcher thread is "dead";
-
strict redlock algorithm support (support for many
RedisClientinstances that are fully independent (distributed redis instances)); - an ability to release all locks and all requests of the concrete acquirer id only or of the concrete host id only (both together:
#clear_locks_of); - detailed lock informotion inside the error object in cases of exceptions (at the moment we have this info inside the error message only that hard to analyze in work);
- a convenient way to mark any
lockinvocation as "non-instrumentable" / "non-loggable" (as an alternative toVoidNotifierand toVoidLogger); -
README-sectionIssues with other Libsabout issues in other libraries that can broke RQL features:-
Sentry's' bugs with Ractors:-
Sentry-OpenTelemetry problems with its global mutexes and non-sharable objects that is not accessible from the ractors (sentry tyies to intercept allredis-clientinvocations managing their logic via global Mutex instance that brokesswarm-modewithnon-sharablememory access errors, cuz RQL's swarm works using its own RedisClient-instnace, that fails isnide theSentry's patch: Sentry tries to use the same Mutex (instantiated inside the main Ractor) from the our non-main Ractor (swar-mode works under the non-main ractor) and this process fails
on non-sharable memory error);
-
-
-
Minor:
-
*_statusaliases for*_infomethods; - an ability to return all insturmentation metrics from the
lockinvocation (and after blockyielding); - think about a PG-like
stats-data/table, that should be helpful for lock history acquirement analyzation 🤔 (suitable for cases when we want to check if the lock was acquired by some different parallel process durign the some period of time in the past or not); - named swarm threads (
Thread#name) and ractors (Ractor#name; the lock keeper thread is already namedrql.lock_keeper) in order to have an ability to find and work with RQL's threads and ractors outside of RQL logic (stop threads before process forking, for example); -
#lock/#lock!-timeout:option: support for granular periods (it supports onlysecondsat the moment, but we needmilliseconds); - Add
after timeout hookability for timeout errors with an ability to access the binding context (if it possibly) of the thread where it failed; - Add
ignore timeout errorsability (for debug purposes); - A special explicit documentation section that will explain and clarify which exceptions can be occured and what cases occurs them (at the moment such cases are explained inside the lock methods documentation that is not really convinient);
- Renaming of some exceptions (such as
RedisQueuedLocks::TimedLockTimeoutError) to make the related problem more quickly, faster and easier to understand; - Support for detailed
OpenTelemetrytracing; -
light mode: an ability to work without any debug and instrumentation logic and data (totally reduced debugging and instrumenting possibilities, but better performance); - support for
Dragonflydatabase backend (https://github.com/dragonflydb/dragonfly) (https://www.dragonflydb.io/); - (research) GVL-isolation for lock acquirement logic (try to bypass Ruby's "context-switching" in order to prevent any time-based affects on lock-acquirement logic);
- Semantic error objects for unexpected Redis errors;
- sized lock queues (with an ability of dynamically growing size);
- better code stylization (+ some refactorings);
-
RedisQueuedLocks::Acquirer::AcquireLock::TryToLock#try_to_lock- detailed successful result analization; - Support for LIFO strategy;
- specs refactoring with 100% test coverage (total specs rework);
- statistics with UI;
- JSON log formatter;
- automatic deadlock detection;
-
go-lang implementation; - (research) simplification and speedup of the internal "redis-communuication-and-data-storing"-based algorithms;
-
unlock_on:-option in lock/lock! logic in order to support auto-unlocking on any exception rasaied under the invoked block (invoked under the lock); -
Research: support for
Valkeydatabase backend (https://github.com/valkey-io/valkey) (https://valkey.io/); -
Research: support for
Garnetdatabase backend (https://microsoft.github.io/) (https://github.com/microsoft/garnet); - add a library-level exception, when RQL-related key in Redis (required for its logic) has incompatible type (means: some other program uses our key with their own type and logic and RQL can't work properly);
- yardoc docs with CI check (full doc coverage check);
- split exception inheritance to the groups:
lock obtaining errors,block invocation errors,swarm errors, and other groups (research possible groups):- in some cases we need to intercept "Lock Obtaining Process Erros", in other cases: "Block Invocation Errors", and so on;
- think about
#debounceand#throttlemechanisms;
-
Build and Develop
[back to top]
- Tests (
RSpec):
bundle exec rake rspec- Tests in parallel processes (
RSpec, ~6x faster): each process (worker) works with its own pair of Redis databases (the specs use db 0 and db 1), soWORKERS=nflushes db0..2n-1of the local Redis (the default number of workers: the Redisdatabases/ 2, up to the CPU count); the examples are distributed by their durations of the previous runs (tmp/rspec_parallel/durations.json), the output of each worker is intmp/rspec_parallel/worker-<n>.log, the coverage report of the whole run is collated intocoverage/after all workers:
bundle exec rake rspec:parallel
WORKERS=4 bundle exec rake rspec:parallel
bundle exec rake "rspec:parallel[spec/redis_queued_locks_spec.rb]" # spec files/filters- Linting (
Rubocop+RBS):
bundle exec rake rubocop-
StaticTypeChecking (Steep):
bundle exec rake steep:check-
RuntimeTypeChecking (RBS):
bundle exec rbs collection install && RBS_TEST_RAISE=true RUBYOPT='-rbundler/setup -rrbs/test/setup' RBS_TEST_OPT='-I sig' RBS_TEST_LOGLEVEL=error RBS_TEST_TARGET='RedisQueuedLocks::*' RBS_TEST_SKIP='::RedisQueuedLocks::Swarm::FlushZombies,::RedisQueuedLocks::Swarm::SwarmElement::Isolated,::RedisQueuedLocks::Swarm::RedisClientBuilder' bundle exec rake rspec:parallel
# parallel processes as in CI: `WORKERS=n` flushes db `0..2n-1` of the local Redis (see the parallel tests above);
# or in one process (db 0 and db 1): the same environment with `bundle exec rspec` instead of `bundle exec rake rspec:parallel`;
# CI also sets `RUBY_TCP_NO_FAST_FALLBACK=1` (no resolver threads per Redis connection: they starve the workers on a small CPU)Contributing
[back to top]
- Fork it ( https://github.com/0exp/redis_queued_locks )
- Create your feature branch (
git checkout -b feature/my-new-feature) - Commit your changes (
git commit -am '[feature_context] Add some feature') - Push to the branch (
git push origin feature/my-new-feature) - Create new Pull Request
License
[back to top]
Released under MIT License.
Authors
[back to top]