cache-coalescer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1523415f0c539633da76fde9e1f0e435be4734ffdffcaa5e02a5ea7695b8aa55
4
+ data.tar.gz: 6e146143145e475412339ad3bc4d24bfa5234769e215cf0b909e1c2f838c031b
5
+ SHA512:
6
+ metadata.gz: 49583cc46cc5a62a6b6433667076f6422937b7b5084c7d066f39aad57e942c1bc6d456722bc2ab8a092efde37fc4bd080b2a630039dc559eafb09e5f0a90e163
7
+ data.tar.gz: 69eebe43f705403d3030f939e6757bbb49458952931a7342d06641170121e38c623c508de09684caf8130be27fea9a20b8fa4bdaf18d8dc9f79474064273d4a9
@@ -0,0 +1,19 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+
7
+ jobs:
8
+ test:
9
+ runs-on: ubuntu-latest
10
+ strategy:
11
+ matrix:
12
+ ruby: ["3.0", "3.1", "3.2", "3.3"]
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: ruby/setup-ruby@v1
16
+ with:
17
+ ruby-version: ${{ matrix.ruby }}
18
+ bundler-cache: true
19
+ - run: bundle exec rspec
data/.gitignore ADDED
@@ -0,0 +1,15 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+
13
+ # bundler
14
+ Gemfile.lock
15
+
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,4 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+ - Initial release.
@@ -0,0 +1,26 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+ We pledge to make participation in our community a harassment-free experience for everyone.
5
+
6
+ ## Our Standards
7
+ Examples of behavior that contributes to a positive environment include:
8
+ - Using welcoming and inclusive language
9
+ - Respecting differing viewpoints and experiences
10
+ - Gracefully accepting constructive criticism
11
+
12
+ Examples of unacceptable behavior include:
13
+ - Trolling, insulting/derogatory comments, and personal or political attacks
14
+ - Public or private harassment
15
+
16
+ ## Enforcement Responsibilities
17
+ Project maintainers are responsible for clarifying and enforcing standards of acceptable behavior.
18
+
19
+ ## Scope
20
+ This Code of Conduct applies within all project spaces and in public spaces when representing the project.
21
+
22
+ ## Enforcement
23
+ Instances of abusive behavior may be reported to the maintainer listed in the gemspec.
24
+
25
+ ## Attribution
26
+ This Code of Conduct is adapted from the Contributor Covenant, version 1.4.
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,10 @@
1
+ # Contributing
2
+
3
+ ## Development setup
4
+ - Run `bundle install`
5
+ - Run `bundle exec rspec`
6
+
7
+ ## Release
8
+ 1. Update `CHANGELOG.md`
9
+ 2. Bump version in `lib/**/version.rb`
10
+ 3. Run `bundle exec rake release`
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in cache-coalescer.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 MounirGaiby
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # Cache Coalescer
2
+
3
+ Distributed singleflight for Rails cache misses to prevent stampedes on cold keys.
4
+
5
+ ## About
6
+ Cache Coalescer ensures only one request computes a missing value while the rest wait for it. The first caller acquires a lock, computes, and writes to cache. Other callers poll briefly and reuse the result. Optional stale values can be served if the lock is held for too long.
7
+
8
+ This is ideal for expensive cache-miss work such as API calls, report generation, or heavyweight database queries.
9
+
10
+ ## Use Cases
11
+ - Prevent thundering herds on cold cache keys
12
+ - Reduce p99 latency spikes during traffic bursts
13
+ - Protect downstream services from request stampedes
14
+ - Coalesce expensive fan-out workloads into a single computation
15
+
16
+ ## Compatibility
17
+ - Ruby 3.0+
18
+ - ActiveSupport 6.1+
19
+ - Works with any ActiveSupport cache store
20
+ - Best with Redis-backed stores for distributed locking
21
+
22
+ ## Installation
23
+ ```ruby
24
+ # Gemfile
25
+
26
+ gem "cache-coalescer"
27
+ ```
28
+
29
+ ## Usage
30
+ ```ruby
31
+ value = Cache::Coalescer.fetch("expensive-key", ttl: 60, lock_ttl: 5, wait_timeout: 2, store: Rails.cache) do
32
+ ExpensiveQuery.call
33
+ end
34
+ ```
35
+
36
+ Rails integration adds `Rails.cache.fetch_coalesced`:
37
+ ```ruby
38
+ Rails.cache.fetch_coalesced("expensive-key", ttl: 60) { ExpensiveQuery.call }
39
+ ```
40
+
41
+ ## Options
42
+ - `ttl` (Integer) cache TTL in seconds
43
+ - `lock_ttl` (Integer) lock expiry in seconds
44
+ - `wait_timeout` (Float) how long waiters poll for a result
45
+ - `wait_sleep` (Float) polling interval in seconds
46
+ - `stale_ttl` (Integer) optional stale window; if set, stale values are returned on timeout
47
+ - `store` ActiveSupport cache store (defaults to `Rails.cache` when available)
48
+ - `lock_client` Redis client or `Cache::Coalescer::Lock::InMemoryLock`
49
+
50
+ ## Locking
51
+ If the cache store exposes `redis`, a Redis lock is used automatically. Otherwise, the gem falls back to an in-memory lock which is safe for single-process usage.
52
+
53
+ ## Release
54
+ ```bash
55
+ bundle exec rake release
56
+ ```
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "cache/coalescer"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path("lib", __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require "cache/coalescer/version"
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = "cache-coalescer"
9
+ spec.version = Cache::Coalescer::VERSION
10
+ spec.authors = ["MounirGaiby"]
11
+ spec.email = ["mounirgaiby@gmail.com"]
12
+
13
+ spec.summary = "Distributed singleflight for Rails cache misses to prevent stampedes."
14
+ spec.description = "Coalesce concurrent cache-miss computations with Redis-backed locks and shared results."
15
+ spec.homepage = "https://github.com/elysium-arc/cache-coalescer"
16
+ spec.license = "MIT"
17
+ spec.required_ruby_version = ">= 3.0"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = "https://github.com/elysium-arc/cache-coalescer"
21
+ spec.metadata["changelog_uri"] = "https://github.com/elysium-arc/cache-coalescer/blob/main/CHANGELOG.md"
22
+ spec.metadata["rubygems_mfa_required"] = "true"
23
+
24
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
25
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
26
+ end
27
+ spec.bindir = "bin"
28
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
29
+ spec.require_paths = ["lib"]
30
+
31
+ spec.add_dependency "activesupport", ">= 6.1"
32
+ spec.add_dependency "redis", ">= 4.0"
33
+
34
+ spec.add_development_dependency "bundler", ">= 1.17"
35
+ spec.add_development_dependency "rake", ">= 13.0"
36
+ spec.add_development_dependency "rspec", "~> 3.12"
37
+ spec.add_development_dependency "simplecov", "~> 0.22"
38
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cache
4
+ module Coalescer
5
+ module Lock
6
+ LUA_RELEASE = <<~LUA
7
+ if redis.call("get", KEYS[1]) == ARGV[1] then
8
+ return redis.call("del", KEYS[1])
9
+ else
10
+ return 0
11
+ end
12
+ LUA
13
+
14
+ def self.default_for(store)
15
+ return RedisLock.new(store.redis) if store.respond_to?(:redis)
16
+ raise Cache::Coalescer::Error, "lock_client is required when store does not expose redis"
17
+ end
18
+
19
+ class RedisLock
20
+ def initialize(redis)
21
+ @redis = redis
22
+ end
23
+
24
+ def acquire(key, token, ttl)
25
+ with_redis do |conn|
26
+ conn.set(key, token, nx: true, px: (ttl * 1000).to_i)
27
+ end
28
+ end
29
+
30
+ def release(key, token)
31
+ with_redis do |conn|
32
+ conn.eval(LUA_RELEASE, keys: [key], argv: [token])
33
+ end
34
+ rescue StandardError
35
+ false
36
+ end
37
+
38
+ private
39
+
40
+ def with_redis
41
+ if @redis.respond_to?(:with)
42
+ @redis.with { |conn| yield conn }
43
+ else
44
+ yield @redis
45
+ end
46
+ end
47
+ end
48
+
49
+ class InMemoryLock
50
+ def initialize
51
+ @mutex = Mutex.new
52
+ @locks = {}
53
+ end
54
+
55
+ def acquire(key, _token, ttl)
56
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
57
+ @mutex.synchronize do
58
+ expires_at = @locks[key]
59
+ return false if expires_at && expires_at > now
60
+ @locks[key] = now + ttl
61
+ true
62
+ end
63
+ end
64
+
65
+ def release(key, _token)
66
+ @mutex.synchronize { @locks.delete(key) }
67
+ true
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ # :nocov:
4
+ begin
5
+ require "rails/railtie"
6
+ rescue LoadError
7
+ end
8
+
9
+ if defined?(Rails::Railtie)
10
+ module Cache
11
+ module Coalescer
12
+ module StoreExtension
13
+ def fetch_coalesced(key, ttl:, **options, &block)
14
+ Cache::Coalescer.fetch(key, ttl: ttl, store: self, **options, &block)
15
+ end
16
+ end
17
+
18
+ class Railtie < Rails::Railtie
19
+ initializer "cache_coalescer.extend_cache" do
20
+ require "active_support/cache"
21
+ ::ActiveSupport::Cache::Store.include(Cache::Coalescer::StoreExtension)
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
27
+ # :nocov:
@@ -0,0 +1,5 @@
1
+ module Cache
2
+ module Coalescer
3
+ VERSION = "0.1.0"
4
+ end
5
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/notifications"
4
+ require "securerandom"
5
+ require "cache/coalescer/version"
6
+ require "cache/coalescer/lock"
7
+
8
+ module Cache
9
+ module Coalescer
10
+ class Error < StandardError; end
11
+
12
+ DEFAULT_LOCK_TTL = 5
13
+ DEFAULT_WAIT_TIMEOUT = 5
14
+ DEFAULT_WAIT_SLEEP = 0.05
15
+
16
+ def self.fetch(key, ttl:, store: nil, lock_ttl: DEFAULT_LOCK_TTL, wait_timeout: DEFAULT_WAIT_TIMEOUT,
17
+ wait_sleep: DEFAULT_WAIT_SLEEP, stale_ttl: nil, lock_client: nil, &block)
18
+ raise ArgumentError, "block required" unless block
19
+
20
+ store ||= default_store
21
+ value = store.read(key)
22
+ return value unless value.nil?
23
+
24
+ lock_client ||= store.respond_to?(:redis) ? Lock.default_for(store) : Lock::InMemoryLock.new
25
+ lock_key = lock_key_for(key)
26
+ token = SecureRandom.uuid
27
+
28
+ if lock_client.acquire(lock_key, token, lock_ttl)
29
+ return compute_and_store(store, key, ttl, stale_ttl, lock_client, lock_key, token, &block)
30
+ end
31
+
32
+ deadline = monotonic + wait_timeout
33
+ loop do
34
+ value = store.read(key)
35
+ return value unless value.nil?
36
+ break if monotonic >= deadline
37
+ sleep wait_sleep
38
+ end
39
+
40
+ if lock_client.acquire(lock_key, token, lock_ttl)
41
+ return compute_and_store(store, key, ttl, stale_ttl, lock_client, lock_key, token, &block)
42
+ end
43
+
44
+ if stale_ttl
45
+ stale_value = store.read(stale_key_for(key))
46
+ return stale_value unless stale_value.nil?
47
+ end
48
+
49
+ nil
50
+ end
51
+
52
+ def self.default_store
53
+ return Rails.cache if defined?(Rails) && Rails.respond_to?(:cache)
54
+ raise Error, "store is required when Rails.cache is unavailable"
55
+ end
56
+
57
+ def self.compute_and_store(store, key, ttl, stale_ttl, lock_client, lock_key, token)
58
+ value = yield
59
+ store.write(key, value, expires_in: ttl)
60
+ if stale_ttl
61
+ store.write(stale_key_for(key), value, expires_in: ttl + stale_ttl)
62
+ end
63
+ value
64
+ ensure
65
+ lock_client.release(lock_key, token) if lock_client
66
+ end
67
+
68
+ def self.lock_key_for(key)
69
+ "cache-coalescer:lock:#{key}"
70
+ end
71
+
72
+ def self.stale_key_for(key)
73
+ "cache-coalescer:stale:#{key}"
74
+ end
75
+
76
+ def self.monotonic
77
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
78
+ end
79
+ end
80
+ end
81
+
82
+ require "cache/coalescer/railtie"
metadata ADDED
@@ -0,0 +1,151 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cache-coalescer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - MounirGaiby
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-02-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '6.1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '6.1'
27
+ - !ruby/object:Gem::Dependency
28
+ name: redis
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '4.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '4.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '1.17'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '1.17'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '13.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '13.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.12'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.12'
83
+ - !ruby/object:Gem::Dependency
84
+ name: simplecov
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '0.22'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '0.22'
97
+ description: Coalesce concurrent cache-miss computations with Redis-backed locks and
98
+ shared results.
99
+ email:
100
+ - mounirgaiby@gmail.com
101
+ executables:
102
+ - console
103
+ - setup
104
+ extensions: []
105
+ extra_rdoc_files: []
106
+ files:
107
+ - ".github/workflows/ci.yml"
108
+ - ".gitignore"
109
+ - ".rspec"
110
+ - CHANGELOG.md
111
+ - CODE_OF_CONDUCT.md
112
+ - CONTRIBUTING.md
113
+ - Gemfile
114
+ - LICENSE.txt
115
+ - README.md
116
+ - Rakefile
117
+ - bin/console
118
+ - bin/setup
119
+ - cache-coalescer.gemspec
120
+ - lib/cache/coalescer.rb
121
+ - lib/cache/coalescer/lock.rb
122
+ - lib/cache/coalescer/railtie.rb
123
+ - lib/cache/coalescer/version.rb
124
+ homepage: https://github.com/elysium-arc/cache-coalescer
125
+ licenses:
126
+ - MIT
127
+ metadata:
128
+ homepage_uri: https://github.com/elysium-arc/cache-coalescer
129
+ source_code_uri: https://github.com/elysium-arc/cache-coalescer
130
+ changelog_uri: https://github.com/elysium-arc/cache-coalescer/blob/main/CHANGELOG.md
131
+ rubygems_mfa_required: 'true'
132
+ post_install_message:
133
+ rdoc_options: []
134
+ require_paths:
135
+ - lib
136
+ required_ruby_version: !ruby/object:Gem::Requirement
137
+ requirements:
138
+ - - ">="
139
+ - !ruby/object:Gem::Version
140
+ version: '3.0'
141
+ required_rubygems_version: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ">="
144
+ - !ruby/object:Gem::Version
145
+ version: '0'
146
+ requirements: []
147
+ rubygems_version: 3.3.3
148
+ signing_key:
149
+ specification_version: 4
150
+ summary: Distributed singleflight for Rails cache misses to prevent stampedes.
151
+ test_files: []