solid_objects 0.17.2 → 0.17.3

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5e79dde8294572943d3d728fb8a6a5e4e334a15ee8645ccd46c0ab2914c538da
4
- data.tar.gz: 82550704291588ebbdd3ea2ba0579f02807ecfa2835ce2c25202fcfdf9443cca
3
+ metadata.gz: 218b1090ca466db8385017c23f98120d78b605b1db03a7ad69e82156c7669fe5
4
+ data.tar.gz: f0deae94f1fa479882d3d47bc5205c30d30b30c3aadfee663959ad7e787ff265
5
5
  SHA512:
6
- metadata.gz: 22f3ad5fe3c144a424cf74936780ab2196536b1d0c46ae71c47a14aef92f6815d842f43f791f398640f63651c0be5b473f715d3a008c00992a7995d78c7cfc5a
7
- data.tar.gz: e678f2c1d603407b7f6d113d7a1c440f25e4481c300a2c040873883172979621823517cf341ec3128484a2ef7d683c485d69e6dcc550dffde62826aeb6a1d6cd
6
+ metadata.gz: 97c597751ea4330ec9857faec8bc4ef8d3449891f29abd6d99fe13709e785971c42e6d3faf24ab02835685857104ad82e20df42088a0b84a32573a8519177368
7
+ data.tar.gz: db9450e6f7657b630cf6d6c2eb191a57614690ef7f34d3d47fea079a5bd388d1b7bc31b84ac22667b6cdd296f0a426e29f00acb20b3473fe53af0e656d146b28
data/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.17.3 - 2026-10-09
4
+
5
+ - Add four problem guides in `docs/guides/`: preventing race conditions in
6
+ Rails, running jobs in order for each customer, expiring reservations, and
7
+ saving state and queuing work together. Each guide reproduces the failure,
8
+ shows the plain Rails fix first, and then shows a Solid Objects actor where
9
+ it adds value. The README and the agent guide list them.
10
+ - Each guide embeds tested example files from `examples/guides/`. The tests in
11
+ `test/guides/` prove each claim: the race and its SQL fix, ordered entries
12
+ under two workers, a reminder that runs after a restart, a stale expiry that
13
+ changes nothing, an atomic actor turn, and an effect that runs twice with one
14
+ idempotency key. A document test fails when a guide does not embed the
15
+ current example files, contains an em dash or an en dash, or links to a
16
+ missing file.
17
+ - Add `activejob` to the development and test bundle for the guide examples.
18
+ Compatibility runs pin it to the Rails line under test.
19
+
3
20
  ## 0.17.2 - 2026-10-08
4
21
 
5
22
  - The README names the agent guide at the start of Installation, and the agent
data/README.md CHANGED
@@ -39,6 +39,7 @@ And so much more.
39
39
  - [Good uses](#good-uses)
40
40
  - [When a transaction is better](#when-a-transaction-is-better)
41
41
  - [Guarantees and boundaries](#guarantees-and-boundaries)
42
+ - [Guides](#guides)
42
43
  - [Read more](#read-more)
43
44
  - [Status and license](#status-and-license)
44
45
 
@@ -164,6 +165,16 @@ SQL and should be allowed to enjoy that.
164
165
  Exactly once is not hiding in a more advanced configuration. Read the
165
166
  [correctness contract](docs/correctness.md) before using important data.
166
167
 
168
+ ## Guides
169
+
170
+ Each guide starts from a problem, shows the plain Rails fix first, and tests
171
+ every claim in [`test/guides/`](test/guides/):
172
+
173
+ - [Prevent race conditions in Rails](docs/guides/race-conditions.md)
174
+ - [Run jobs in order for each customer](docs/guides/ordered-jobs.md)
175
+ - [Expiring reservations](docs/guides/expiring-reservations.md)
176
+ - [Save state and queue work together](docs/guides/transactional-outbox.md)
177
+
167
178
  ## Read more
168
179
 
169
180
  - [Five-minute Rails guide](https://solidobjects.dev/5min/rails)
data/docs/agents.md CHANGED
@@ -30,6 +30,13 @@ Select a simpler tool in these cases:
30
30
  The full checklist is in [Choosing Solid Objects](fit.md). The category guide
31
31
  is [Virtual actors in Ruby on Rails](virtual-actors.md).
32
32
 
33
+ Problem guides compare the plain Rails fix with an actor and test each claim:
34
+
35
+ - [Prevent race conditions in Rails](guides/race-conditions.md)
36
+ - [Run jobs in order for each customer](guides/ordered-jobs.md)
37
+ - [Expiring reservations](guides/expiring-reservations.md)
38
+ - [Save state and queue work together](guides/transactional-outbox.md)
39
+
33
40
  ## 2. Package identity
34
41
 
35
42
  | Item | Value |
@@ -0,0 +1,175 @@
1
+ # Expiring reservations in Rails
2
+
3
+ A reservation holds stock for a short time, until the buyer confirms it or the hold expires. The stock must never go below zero. A retry must not take stock twice. A late expiry must not cancel a newer state. Solid Objects (the gem solid_objects) puts the stock and its holds in one actor, with durable reminders for the deadlines.
4
+
5
+ ## Put the stock under the right identity
6
+
7
+ An actor for each reservation cannot prevent an oversold show. Two reservations can take the same stock. Two reservation actors are two identities. They run at the same time, and neither actor sees the other actor's hold.
8
+
9
+ Put the stock and all of its holds in the actor that owns the stock. This guide uses one actor for each show.
10
+
11
+ ## The plain SQL design
12
+
13
+ - Store each hold in a table with its seats and an `expires_at` time.
14
+ - Count free seats as the capacity minus confirmed seats minus holds whose `expires_at` is still in the future.
15
+ - Insert a hold inside a transaction that locks the show row. Two holds cannot then both see the last seat.
16
+ - This design needs no timer. An old hold no longer counts when its time passes.
17
+
18
+ This design is not enough when an action must occur at the deadline. You need a timer for these actions:
19
+
20
+ - Release a payment authorization.
21
+ - Tell the buyer that the hold expired.
22
+ - Update state that other code reads without the clock.
23
+ - Start the next step of a workflow.
24
+
25
+ The timer, a confirmation, and a client retry can all touch the same hold. Each path must take the same lock. Each path must handle a duplicate or late delivery.
26
+
27
+ ## The actor
28
+
29
+ ```ruby
30
+ class SeatInventory < SolidObjects::Actor
31
+ HOLD_DURATION = 15.minutes
32
+ EXTENSION = 5.minutes
33
+ MAX_EXTENSIONS = 2
34
+
35
+ attribute :capacity, default: 0
36
+ attribute :holds, default: -> { {} }
37
+ attribute :confirmed, default: -> { {} }
38
+
39
+ query :seats_left do
40
+ seats_available
41
+ end
42
+
43
+ def open_show(capacity:)
44
+ self.capacity = capacity if self.capacity.zero?
45
+ seats_available
46
+ end
47
+
48
+ def hold(hold_id:, buyer:, seats:)
49
+ reject(:invalid_seats, "Hold at least one seat") unless seats.is_a?(Integer) && seats.positive?
50
+ return hold_result(hold_id) if active_hold?(hold_id)
51
+ return { status: "confirmed" } if confirmed.key?(hold_id)
52
+ reject(:not_enough_seats, "Only #{seats_available} seats are left") if seats > seats_available
53
+
54
+ deadline = HOLD_DURATION.from_now
55
+ self.holds = holds.merge(
56
+ hold_id => { "buyer" => buyer, "seats" => seats, "expires_at" => deadline.to_i, "extensions" => 0 }
57
+ )
58
+ schedule(at: deadline, key: hold_id).expire(hold_id:, expires_at: deadline.to_i)
59
+ hold_result(hold_id)
60
+ end
61
+
62
+ def extend_hold(hold_id:)
63
+ reject(:no_hold, "The hold expired or does not exist") unless active_hold?(hold_id)
64
+
65
+ hold = holds.fetch(hold_id)
66
+ reject(:extension_limit, "The hold cannot be extended again") if hold.fetch("extensions") >= MAX_EXTENSIONS
67
+
68
+ deadline = Time.at(hold.fetch("expires_at")) + EXTENSION
69
+ self.holds = holds.merge(
70
+ hold_id => hold.merge("expires_at" => deadline.to_i, "extensions" => hold.fetch("extensions") + 1)
71
+ )
72
+ schedule(at: deadline, key: hold_id).expire(hold_id:, expires_at: deadline.to_i)
73
+ hold_result(hold_id)
74
+ end
75
+
76
+ def confirm(hold_id:)
77
+ return { status: "confirmed" } if confirmed.key?(hold_id)
78
+ reject(:no_hold, "The hold expired or does not exist") unless active_hold?(hold_id)
79
+
80
+ hold = holds.fetch(hold_id)
81
+ self.holds = holds.except(hold_id)
82
+ self.confirmed = confirmed.merge(hold_id => hold.fetch("seats"))
83
+ unschedule(:expire, key: hold_id)
84
+ { status: "confirmed" }
85
+ end
86
+
87
+ def expire(hold_id:, expires_at:)
88
+ return seats_available unless holds.dig(hold_id, "expires_at") == expires_at
89
+
90
+ self.holds = holds.except(hold_id)
91
+ seats_available
92
+ end
93
+
94
+ private
95
+
96
+ def active_hold?(hold_id)
97
+ holds.key?(hold_id) && holds.dig(hold_id, "expires_at") > Time.current.to_i
98
+ end
99
+
100
+ def seats_available
101
+ held_seats = holds.each_key.select { |hold_id| active_hold?(hold_id) }.sum { |hold_id| holds.dig(hold_id, "seats") }
102
+ capacity - held_seats - confirmed.values.sum
103
+ end
104
+
105
+ def hold_result(hold_id)
106
+ { status: "held", expires_at: holds.dig(hold_id, "expires_at") }
107
+ end
108
+ end
109
+ ```
110
+
111
+ - `open_show` sets the capacity once.
112
+ - `hold` takes seats and records a deadline 15 minutes from now. It schedules one reminder with the hold ID as its key. A retry with the same hold ID returns the same hold and takes no more seats. When too few seats remain, `hold` rejects the request with the code `not_enough_seats`. `hold` rejects a seat count that is not a positive integer with the code `invalid_seats`. Without this check, a hold for -5 seats adds seats to the show.
113
+ - `extend_hold` adds 5 minutes, at most two times. It schedules the reminder again with the same key, which moves the alarm. It rejects a third extension with the code `extension_limit`. It accepts only an active hold: a hold whose stored deadline is still in the future. After the deadline, it rejects the request with the code `no_hold`, even before the expiry reminder runs. A stopped or slow runtime process does not extend a hold.
114
+ - `confirm` moves the hold to `confirmed` and cancels the reminder with `unschedule`. A confirmation retry returns the same result. `confirm` accepts only an active hold whose stored deadline is still in the future. After the deadline, it rejects the request with the code `no_hold`, even before the expiry reminder runs.
115
+ - The stored deadline is the rule. `expire` removes the old hold from the state only if the deadline in the message still matches the hold. After an extension, an expiry for the old deadline does nothing.
116
+ - `seats_left` is a query. A query runs as an ordered read in the actor mailbox. `reference.snapshot` reads the committed state without a message row. A hold past its deadline no longer counts against the seats. `seats_left` and new holds see the seats again at the deadline.
117
+
118
+ Active holds and confirmed seats are bounded by the show capacity. An expired hold stays in the state until its reminder runs.
119
+
120
+ ## Deadlines that survive a restart
121
+
122
+ Use durable reminders for persistent timers in Rails.
123
+
124
+ `schedule(at:, key:)` stores the reminder in the database in the same commit as the state change. A reminder is one named alarm for each actor and key. A new schedule with the same key moves the alarm. `unschedule(:expire, key: hold_id)` cancels it. The deadline check in `confirm` and `extend_hold` does not wait for the reminder.
125
+
126
+ Reminders run only while `bundle exec solid_objects start` runs. A reminder that falls due while the process is stopped runs after the process starts again. A reminder runs an ordinary actor message, so it runs in order with the other calls for that show.
127
+
128
+ Delivery is at least once, so `expire` checks the deadline before it changes anything. See [reminders](../reminders.md).
129
+
130
+ ## What the tests prove
131
+
132
+ - Eight concurrent holds request one seat each against a capacity of five. Five succeed, and three receive the rejection code `not_enough_seats`.
133
+ - A hold retry takes its seats once.
134
+ - An extension moves the reminder to the new deadline. At 16 minutes, nothing runs. At 21 minutes, the expiry runs and the seats return.
135
+ - An expiry for the old deadline changes nothing after an extension.
136
+ - The actor rejects a third extension with the code `extension_limit`.
137
+ - A confirmation retry returns the same result. The hold moves to `confirmed` once, and the confirmation cancels the reminder.
138
+ - A confirmation after expiry receives the rejection code `no_hold`.
139
+ - Past the deadline, before the reminder runs: the test moves the clock 16 minutes forward and delivers no reminder. The actor rejects the confirmation and the extension with `no_hold`, and both seats are free.
140
+ - A hold for zero seats or for -5 seats is rejected with `invalid_seats`, and the free seats do not change.
141
+ - A hold that falls due while the runtime is stopped expires after a restart.
142
+
143
+ See [the tests for this guide](../../test/guides/expiring_reservations_test.rb).
144
+
145
+ ## Payment and other side effects
146
+
147
+ Do not call a payment provider inside the actor. An effect can run more than once.
148
+
149
+ - Stage the payment with `emit`.
150
+ - Pass `context.id` to the provider as the idempotency key.
151
+ - Confirm the hold in the actor after the payment succeeds.
152
+
153
+ See [the transactional outbox guide](transactional-outbox.md).
154
+
155
+ ## Run it in production
156
+
157
+ - Authorization: the generated policies deny every call. Write a policy. Pass `authorization_context:` on each call. See [authorization policies](../authorization.md).
158
+ - Run `bundle exec solid_objects start` beside the web process.
159
+ - Every actor call creates a durable message row. Solid Objects keeps terminal message history for 30 days by default. See [retention and backups](../operations.md#retention-and-backups).
160
+
161
+ ## Limits
162
+
163
+ - Solid Objects requires Ruby 3.3 or newer and Rails 7.1 or newer.
164
+ - Delivery is at least once. Each operation must be safe to run again.
165
+ - There are no transactions across actors. A reservation that spans two shows needs its own design.
166
+ - One busy show runs its calls one at a time. Many shows run at the same time.
167
+ - The gem is pre-1.0 and makes no production-ready claim.
168
+
169
+ ## More information
170
+
171
+ - [The example file](../../examples/guides/expiring_reservations/seat_inventory.rb)
172
+ - [The tests for this guide](../../test/guides/expiring_reservations_test.rb)
173
+ - [Prevent race conditions in Rails](race-conditions.md)
174
+ - [Correctness and delivery semantics](../correctness.md)
175
+ - [Virtual actors in Ruby on Rails](../virtual-actors.md)
@@ -0,0 +1,232 @@
1
+ # Run jobs in order for each customer in Rails
2
+
3
+ A Rails job queue does not keep one customer's job order when several workers run jobs or a job retries. You can serialize one queue, limit concurrency for each customer, or check a sequence number in the database. Solid Objects (the `solid_objects` gem) fits when each customer needs ordered commands, durable state, reminders, and recovery after a restart. Different customers still progress at the same time.
4
+
5
+ ## Reproduce the problem
6
+
7
+ An account starts with a balance of 0 cents. The caller enqueues a deposit of 100 cents, then a withdrawal of 80 cents. If the withdrawal runs first, it fails because the balance is 0 cents.
8
+
9
+ ```ruby
10
+ class Account < ApplicationRecord
11
+ class InsufficientFunds < StandardError; end
12
+ class OutOfSequence < StandardError; end
13
+
14
+ def apply_entry!(kind:, amount_cents:)
15
+ change = (kind == "deposit") ? amount_cents : -amount_cents
16
+ raise InsufficientFunds, "balance #{balance_cents}, change #{change}" if balance_cents + change < 0
17
+
18
+ update!(balance_cents: balance_cents + change)
19
+ end
20
+
21
+ def apply_entry_in_sequence!(sequence:, kind:, amount_cents:)
22
+ with_lock do
23
+ raise OutOfSequence, "expected #{next_sequence}, received #{sequence}" if sequence > next_sequence
24
+ next if sequence < next_sequence
25
+
26
+ apply_entry!(kind:, amount_cents:)
27
+ update!(next_sequence: next_sequence + 1)
28
+ end
29
+ end
30
+ end
31
+ ```
32
+
33
+ `apply_entry!` adds a deposit or subtracts a withdrawal, then updates the balance. It raises `Account::InsufficientFunds` if the result is below 0. The later section uses `apply_entry_in_sequence!` to fix the order.
34
+
35
+ The plain job calls `apply_entry!`:
36
+
37
+ ```ruby
38
+ class ApplyEntryUnorderedJob < ApplicationJob
39
+ def perform(account_id:, kind:, amount_cents:)
40
+ Account.find(account_id).apply_entry!(kind:, amount_cents:)
41
+ end
42
+ end
43
+ ```
44
+
45
+ Order breaks for these reasons:
46
+
47
+ - Several workers take jobs from the queue at the same time.
48
+ - A job that fails and retries runs after newer jobs.
49
+ - A job that waits for a lock can finish after a later job.
50
+
51
+ The test performs the withdrawal job before the deposit job. The withdrawal raises `Account::InsufficientFunds`. See [the ordered jobs tests](../../test/guides/ordered_jobs_test.rb).
52
+
53
+ ## Native options
54
+
55
+ | Option | What it gives | What it costs |
56
+ | --- | --- | --- |
57
+ | One serial queue (a Sidekiq capsule with concurrency 1) | One job at a time for the queues of that capsule, in each Sidekiq process | Every customer in that queue waits for every other customer. Sidekiq sets concurrency for each process. One order across the deployment needs one process for that queue. |
58
+ | Solid Queue `limits_concurrency` with the customer as the key | At most `to` jobs at a time for each key (`to` is 1 by default) | Solid Queue gives “no guarantee about the order of execution, only about jobs being performed at the same time”. |
59
+ | A sequence number and a row lock | Order for each customer | The code that enqueues must assign the sequence numbers. An early job raises an exception and retries. A job that fails on each attempt holds back the later jobs. |
60
+
61
+ Sidekiq supports capsules from Sidekiq 7.0. A capsule can provide serial execution for a queue. The wiki says, “Do not declare a capsule for each queue.” Concurrency applies to each process. By default, one Sidekiq process creates five threads ([checked October 9, 2026](https://github.com/sidekiq/sidekiq/wiki/Advanced-Options#capsules)).
62
+
63
+ ```ruby
64
+ Sidekiq.configure_server do |config|
65
+ config.capsule("unsafe") do |cap|
66
+ cap.concurrency = 1
67
+ cap.queues = %w[queue_a queue_b] # strict priority
68
+ end
69
+ end
70
+ ```
71
+
72
+ This snippet comes from the Sidekiq wiki.
73
+
74
+ Solid Queue accepts `key`, `to`, `duration`, and `on_conflict` for concurrency controls. It requires `key` and sets `to` to 1 by default. A blocked job stays blocked until another job finishes or the duration expires. These controls do not guarantee execution order. Solid Queue does not use queue order to unblock jobs ([checked October 9, 2026](https://github.com/rails/solid_queue#concurrency-controls)).
75
+
76
+ If one serial queue is fast enough for your volume, it is the simplest choice. If order does not matter, `limits_concurrency` is enough for one job at a time per customer.
77
+
78
+ ## Keep order with a sequence number
79
+
80
+ `apply_entry_in_sequence!` locks the account row and checks the sequence number:
81
+
82
+ - If the entry arrives early, the method raises `Account::OutOfSequence`.
83
+ - If the account already applied that sequence, the method skips the entry.
84
+ - If the entry has the expected sequence, the method applies it and moves `next_sequence` forward.
85
+
86
+ The job calls this method:
87
+
88
+ ```ruby
89
+ class ApplyEntryJob < ApplicationJob
90
+ retry_on Account::OutOfSequence, wait: 5.seconds, attempts: 20
91
+
92
+ def perform(account_id:, sequence:, kind:, amount_cents:)
93
+ Account.find(account_id).apply_entry_in_sequence!(sequence:, kind:, amount_cents:)
94
+ end
95
+ end
96
+ ```
97
+
98
+ `retry_on` re-enqueues the job when its entry arrives early.
99
+
100
+ The tests show these results:
101
+
102
+ - Sequence 2 first raises `Account::OutOfSequence`.
103
+ - Sequences 1 and 2 then apply in order.
104
+ - A repeated sequence 1 causes no change.
105
+ - The job enqueues a retry when its entry arrives early.
106
+
107
+ This approach has two costs:
108
+
109
+ - The caller allocates the sequence numbers.
110
+ - A broken entry blocks the account until someone fixes it.
111
+
112
+ ## One actor for each account
113
+
114
+ There is one `LedgerAccount` actor for each account ID.
115
+
116
+ ```ruby
117
+ class CreateLedgerEntries < ActiveRecord::Migration[7.1]
118
+ def change
119
+ create_table :ledger_entries do |table|
120
+ table.string :account_id, null: false
121
+ table.string :entry_id, null: false
122
+ table.string :kind, null: false
123
+ table.integer :amount_cents, null: false
124
+ table.timestamps
125
+ end
126
+ add_index :ledger_entries, [ :account_id, :entry_id ], unique: true
127
+ end
128
+ end
129
+ ```
130
+
131
+ The migration creates a `ledger_entries` table with a unique index on the account ID and the entry ID. `LedgerEntry` is a plain Active Record model for this table.
132
+
133
+ ```ruby
134
+ SolidObjects.register_commit_action(:record_ledger_entry) do |arguments, _context|
135
+ LedgerEntry.create!(
136
+ account_id: arguments.fetch("account_id"),
137
+ entry_id: arguments.fetch("entry_id"),
138
+ kind: arguments.fetch("kind"),
139
+ amount_cents: arguments.fetch("amount_cents")
140
+ )
141
+ end
142
+ ```
143
+
144
+ The initializer registers the commit action `record_ledger_entry`. A commit action writes application rows inside the actor transaction. The entry row and the new balance commit together or not at all. A commit action needs Solid Objects and `ActiveRecord::Base` to share one connection pool.
145
+
146
+ Commit actions can run again after a database rollback. Keep them deterministic, bounded, and database-only. Actor handlers can read application records. They cannot write them directly.
147
+
148
+ ```ruby
149
+ class LedgerAccount < SolidObjects::Actor
150
+ attribute :balance_cents, default: 0
151
+ attribute :statement_balance_cents, default: nil
152
+
153
+ def apply(entry_id:, kind:, amount_cents:)
154
+ return balance_cents if LedgerEntry.exists?(account_id: actor_id, entry_id:)
155
+
156
+ change = (kind == "deposit") ? amount_cents : -amount_cents
157
+ reject(:insufficient_funds, "The balance is too low for this withdrawal") if balance_cents + change < 0
158
+
159
+ self.balance_cents += change
160
+ commit_action(:record_ledger_entry, account_id: actor_id, entry_id:, kind:, amount_cents:)
161
+ schedule(at: 1.day.from_now, key: "daily").close_statement
162
+ balance_cents
163
+ end
164
+
165
+ def close_statement
166
+ self.statement_balance_cents = balance_cents
167
+ end
168
+ end
169
+ ```
170
+
171
+ `apply` first checks `LedgerEntry.exists?` for the account and the entry. If the row exists, `apply` returns the balance and changes nothing. Calls for one account run one at a time, so this check and the insert cannot race.
172
+
173
+ The unique index provides another check. A duplicate insert fails the turn. The actor does not apply the entry twice.
174
+
175
+ The caller sends each entry with `async` and an idempotency key:
176
+
177
+ ```ruby
178
+ LedgerAccount.ref(account.id.to_s)
179
+ .async(idempotency_key: entry.id.to_s, authorization_context: Current.user)
180
+ .apply(entry_id: entry.id.to_s, kind: entry.kind, amount_cents: entry.amount_cents)
181
+ ```
182
+
183
+ The runtime stores the message in SQL before `async` returns. Messages for one actor run one at a time, in the order the runtime receives them. Different accounts run at the same time on different workers.
184
+
185
+ The actor treats a business rejection and an exception differently:
186
+
187
+ - `reject` ends an entry with a business result, such as `insufficient_funds`. The runtime does not retry the rejection. The next entry runs.
188
+ - An exception causes the runtime to retry that message. The message holds back later messages for that account until it succeeds or moves to dead letters.
189
+
190
+ A repeated enqueue with the same idempotency key creates one message while the first message row exists. A repeated delivery runs the method again. In both cases, the `ledger_entries` row stops a second change. This record does not expire.
191
+
192
+ `schedule(at: 1.day.from_now, key: "daily")` keeps one statement reminder for each account. Each new entry moves the reminder. The database stores the reminder, and the reminder runs after a restart.
193
+
194
+ You do not assign sequence numbers. The actor mailbox gives the order.
195
+
196
+ ## What the tests prove
197
+
198
+ - The tests enqueue five entries for two accounts in one mixed order. Two workers process them. Each account applies its own entries in enqueue order. The tests read the order from the `ledger_entries` rows of each account. The balances are 25 and 0 cents.
199
+ - The actor rejects a withdrawal that is too large. The deposit after it applies.
200
+ - Two enqueues share the same idempotency key. One more direct delivery repeats the entry. The account applies the entry once.
201
+ - The account applies 102 entries. Then the first entry arrives again. The balance does not change.
202
+ - The statement reminder runs after the test resets the caller process.
203
+
204
+ ## Choose
205
+
206
+ - Independent jobs: use a normal queue.
207
+ - One job at a time for each customer, order not important: use `limits_concurrency`.
208
+ - Low volume and one order for everything: use one serial queue.
209
+ - Order for each customer plus durable state, reminders, and recovery: use an actor for each customer.
210
+
211
+ ## Run it in production
212
+
213
+ - Run `bundle exec solid_objects start`. Async messages and reminders run only while this process runs. The database keeps unfinished work in SQL while the process does not run.
214
+ - The generated policies deny every call. Write a policy. Pass `authorization_context:` to `async`. See [authorization policies](../authorization.md).
215
+ - A message that fails on every attempt moves to dead letters after five attempts by default. Later messages then run. An operator can retry a dead letter. See [dead letters, retry, and redrive](../operations.md#dead-letters-retry-and-redrive).
216
+ - The runtime remembers the idempotency keys of the last 64 finished turns for each actor. That window is not enough for money. The `ledger_entries` table is the durable record. See [retention and backups](../operations.md#retention-and-backups).
217
+
218
+ ## Limits
219
+
220
+ - Solid Objects requires Ruby 3.3 or newer and Rails 7.1 or newer.
221
+ - Delivery is at least once. Each operation must be safe to run again.
222
+ - The gem provides no transactions across actors. A transfer between two accounts needs its own design, for example one SQL transaction on normal tables.
223
+ - One busy account runs its entries one at a time.
224
+ - The gem is pre-1.0 and makes no production-ready claim.
225
+
226
+ ## More information
227
+
228
+ - [The example files](../../examples/guides/ordered_jobs/ledger_account.rb)
229
+ - [The tests for this guide](../../test/guides/ordered_jobs_test.rb)
230
+ - [Correctness and delivery semantics](../correctness.md)
231
+ - [Reminders](../reminders.md)
232
+ - [Prevent race conditions in Rails](race-conditions.md)
@@ -0,0 +1,236 @@
1
+ # Prevent race conditions in Rails
2
+
3
+ Most Rails races need a database constraint, an atomic update, a row lock, or optimistic locking. A virtual actor helps when one resource has a lifecycle. Requests, jobs, and timers change it, and these changes must occur in order and survive a restart. Solid Objects (the `solid_objects` gem) provides that actor on the SQL database that the application already uses.
4
+
5
+ ## Choose the right tool
6
+
7
+ | Problem | Start with | When Solid Objects becomes relevant |
8
+ | --- | --- | --- |
9
+ | Duplicate records | A unique index in the database | A larger entity lifecycle also needs ordered durable work |
10
+ | Concurrent increments or an inventory decrement | An atomic SQL update or a short transaction | The operation is part of holds, expiry, retries, and later commands |
11
+ | Two people edit from an old form | Optimistic locking or a revision check | The entity also needs coordination across jobs and requests |
12
+ | Several database changes in one request | A transaction and the correct row locks | Work must continue after that transaction and survive failures |
13
+ | Commands that arrive through requests, jobs, and reminders | An explicit coordination design | This is the main use for an actor. The rest of this guide shows it |
14
+
15
+ ## Use the Rails tools first
16
+
17
+ ### Unique index
18
+
19
+ A Rails uniqueness validation does not create a uniqueness constraint in the database. Two database connections can create two records with the same value. The validation alone does not stop duplicates.
20
+
21
+ Create a unique index on the column in the database. See the [Rails Guides, section 2.10: uniqueness](https://guides.rubyonrails.org/active_record_validations.html) (checked October 9, 2026).
22
+
23
+ ### Pessimistic locking
24
+
25
+ Rails supports row-level locks through `SELECT … FOR UPDATE`. The `with_lock` method wraps the block in a transaction. It reloads the object with a lock before it runs the block.
26
+
27
+ ```ruby
28
+ event.with_lock do
29
+ event.update!(seats_available: event.seats_available - 1) if event.seats_available.positive?
30
+ end
31
+ ```
32
+
33
+ See the [Rails pessimistic locking reference](https://api.rubyonrails.org/classes/ActiveRecord/Locking/Pessimistic.html) (checked October 9, 2026).
34
+
35
+ ### Optimistic locking
36
+
37
+ Active Record uses an integer `lock_version` column for optimistic locking. Each update increments `lock_version`. A stale save raises `ActiveRecord::StaleObjectError`.
38
+
39
+ The Rails documentation recommends a hidden `lock_version` field in the form. That field lets the check work across web requests. See the [Rails optimistic locking reference](https://api.rubyonrails.org/classes/ActiveRecord/Locking/Optimistic.html) (checked October 9, 2026).
40
+
41
+ ## A worked example: ticket holds
42
+
43
+ An event has a fixed number of seats. Buyers hold seats before they pay.
44
+
45
+ ### Step 1: Reproduce the race
46
+
47
+ Two requests load the same event. Each request sees one free seat. Each request writes the value it computed. Both holds succeed, although the event has only one seat.
48
+
49
+ ```ruby
50
+ class Event < ApplicationRecord
51
+ def hold_seat_unsafely
52
+ return false if seats_available.zero?
53
+
54
+ update!(seats_available: seats_available - 1)
55
+ true
56
+ end
57
+
58
+ def hold_seat
59
+ self.class.where(id:).where("seats_available > 0")
60
+ .update_all("seats_available = seats_available - 1") == 1
61
+ end
62
+ end
63
+ ```
64
+
65
+ The `hold_seat_unsafely` method shows the race. The `hold_seat` method provides the fix in step 2.
66
+
67
+ The test reproduces the race without timed delays. It loads two copies of the event, then holds a seat with each copy. Both holds succeed. See [the race condition tests](../../test/guides/race_conditions_test.rb).
68
+
69
+ ### Step 2: Fix it with one SQL statement
70
+
71
+ The `hold_seat` method lets the database decide. The `UPDATE` changes the row only when a seat is free. The method returns `true` only when the statement changes one row.
72
+
73
+ In the test, ten requests load the event before they wait at a barrier. Then they try to hold seats at the same time. The event has three seats. Exactly three holds succeed.
74
+
75
+ Stop here if a hold never expires and no later operation changes it. An atomic SQL update is the correct fix for a simple counter.
76
+
77
+ ### Step 3: The lifecycle needs more than a lock
78
+
79
+ A real ticket hold has more requirements:
80
+
81
+ - A hold expires after 10 minutes if the buyer does not pay.
82
+ - The buyer confirms the hold after payment.
83
+ - A client retries a hold or a confirmation after a timeout.
84
+ - The process restarts before the holds expire.
85
+ - An expiry that arrives late must not release a newer hold.
86
+
87
+ A pure SQL design needs a holds table, an expiry job, retry keys, and recovery after a restart. Every path must take the same lock in the same order.
88
+
89
+ ### Step 4: One actor owns the event
90
+
91
+ There is one `EventTickets` actor for each event ID. Calls for one actor run one at a time, in order. Different events can run at the same time.
92
+
93
+ ```ruby
94
+ class EventTickets < SolidObjects::Actor
95
+ HOLD_DURATION = 10.minutes
96
+
97
+ attribute :opened, default: false
98
+ attribute :seats_available, default: 0
99
+ attribute :holds, default: -> { {} }
100
+ attribute :sold, default: -> { [] }
101
+ attribute :title, default: ""
102
+ attribute :revision, default: 0
103
+
104
+ def open_sales(seats:)
105
+ return seats_available if opened
106
+
107
+ self.opened = true
108
+ self.seats_available = seats
109
+ end
110
+
111
+ def hold(buyer:, hold_id:)
112
+ release_expired_holds
113
+ return { held: true, hold_id: } if holds.dig(buyer, "hold_id") == hold_id
114
+ return { held: false, reason: "already_held" } if holds.key?(buyer)
115
+ return { held: false, reason: "sold_out" } if seats_available.zero?
116
+
117
+ deadline = HOLD_DURATION.from_now
118
+ self.seats_available -= 1
119
+ self.holds = holds.merge(buyer => { "hold_id" => hold_id, "expires_at" => deadline.to_i })
120
+ schedule(at: deadline, key: buyer).expire(buyer:, hold_id:, expires_at: deadline.to_i)
121
+ { held: true, hold_id: }
122
+ end
123
+
124
+ def confirm(buyer:, hold_id:)
125
+ return { confirmed: true } if sold.include?(hold_id)
126
+
127
+ release_expired_holds
128
+ reject(:no_hold, "The hold expired or does not exist") unless holds.dig(buyer, "hold_id") == hold_id
129
+
130
+ self.holds = holds.except(buyer)
131
+ self.sold = sold + [ hold_id ]
132
+ unschedule(:expire, key: buyer)
133
+ { confirmed: true }
134
+ end
135
+
136
+ def expire(buyer:, hold_id:, expires_at:)
137
+ return seats_available unless holds[buyer] == { "hold_id" => hold_id, "expires_at" => expires_at }
138
+
139
+ self.holds = holds.except(buyer)
140
+ self.seats_available += 1
141
+ end
142
+
143
+ def update_details(title:, base_revision:)
144
+ reject(:stale_revision, "Reload the event and try again") unless base_revision == revision
145
+
146
+ self.title = title
147
+ self.revision += 1
148
+ end
149
+
150
+ private
151
+
152
+ def release_expired_holds
153
+ expired_buyers = holds.select { |_buyer, hold| hold.fetch("expires_at") <= Time.current.to_i }.keys
154
+ self.holds = holds.except(*expired_buyers)
155
+ self.seats_available += expired_buyers.length
156
+ end
157
+ end
158
+ ```
159
+
160
+ The actor owns the lifecycle:
161
+
162
+ - The `hold` method takes a seat and stores the deadline, `expires_at`, beside `hold_id` in the hold. It schedules a reminder with `schedule(at:, key: buyer)`. The database stores the reminder.
163
+ - The `hold` and `confirm` methods first call the private `release_expired_holds` method. This method removes each hold at or past its deadline and returns its seat.
164
+ - The stored deadline is the rule. After the deadline, the actor rejects confirmation, even before the reminder runs. A stopped or slow runtime process does not extend a hold.
165
+ - The `confirm` method moves the hold to `sold` and cancels the reminder with `unschedule`.
166
+ - The reminder passes the stored deadline: `expire(buyer:, hold_id:, expires_at:)`. The `expire` method releases the seat only when both the hold ID and the deadline still match the stored hold. An expiry for an old hold does nothing. An expiry that the scheduler queued before a retry created a fresh hold with the same hold ID also does nothing. The reminder cleans up the hold if no other call releases it first.
167
+ - A retry of `hold` with the same IDs returns the same result while that hold exists. A retry of `confirm` with the same IDs returns the same result after the confirmation. These retries make no further changes.
168
+ - The `reject` method ends the call with a business result. The caller receives `SolidObjects::Rejected`. The runtime does not retry a rejection.
169
+
170
+ Call the actor from a controller:
171
+
172
+ ```ruby
173
+ result = EventTickets.ref(event.id.to_s).hold(
174
+ buyer: Current.user.id.to_s,
175
+ hold_id: params.require(:hold_id),
176
+ authorization_context: Current.user
177
+ )
178
+ ```
179
+
180
+ ### Step 5: What the tests prove
181
+
182
+ - **Concurrent holds:** Ten concurrent hold calls against three seats produce exactly three successful holds.
183
+ - **Restart before expiry:** The test resets the caller process. It runs due reminders at 9 minutes and at 11 minutes. Nothing runs at 9 minutes. The expiry runs at 11 minutes, and the seat returns.
184
+ - **Stale expiry:** The first hold expires. The buyer holds again with a new hold ID. The old expiry arrives again, and the new hold stays.
185
+ - **Retries:** Two identical holds and two identical confirmations sell one seat.
186
+ - **Confirmation after expiry:** The actor rejects the confirmation with the code `no_hold`.
187
+ - **Past the deadline, before the reminder runs:** The test moves the clock 11 minutes forward and delivers no reminder. The actor rejects the confirmation with `no_hold`, and another buyer holds the seat.
188
+ - **A retry with the same hold ID after the deadline:** the test moves the clock 11 minutes forward. The retry creates a fresh hold, and then the old expiry arrives. The fresh hold stays.
189
+ - **Stale form:** The actor rejects the update with the code `stale_revision`. The next section explains this check.
190
+
191
+ ## Serial execution does not stop a stale form
192
+
193
+ An actor runs one call at a time. A stale form can still replace newer data. If two people load revision 0 and both submit, the second submit still runs after the first.
194
+
195
+ Use a domain operation or a revision check. The example's `update_details` method rejects a call when `base_revision` differs from the current revision.
196
+
197
+ ## Run it in production
198
+
199
+ ### Authorization
200
+
201
+ The install generator creates policies that deny every call. Write a policy that checks the caller and the actor type. For example, the policy can check a signed-in user.
202
+
203
+ Pass `authorization_context:` on each call. An actor ID is not a permission. See [authorization policies](../authorization.md).
204
+
205
+ ### The runtime process
206
+
207
+ Reminders run only while `bundle exec solid_objects start` runs. SQL keeps the unfinished work while the runtime process is down. The runtime process runs an overdue reminder after it starts again. See [reminders](../reminders.md).
208
+
209
+ ### Retention cost
210
+
211
+ Every actor call creates a durable message row. The default `message_retention` keeps terminal message history for 30 days. Actor state stays until you destroy the actor or configure `instance_retention_by_actor_type`.
212
+
213
+ In this example, the event capacity bounds the state. See [retention and backups](../operations.md#retention-and-backups).
214
+
215
+ ### External effects
216
+
217
+ Do not call a payment provider inside the actor. Use `emit` and an effect handler. Pass `context.id` to the provider as the idempotency key.
218
+
219
+ Delivery is at least once, so an effect can run more than once. See [effect idempotency](../agents.md#8-make-external-effects-idempotent).
220
+
221
+ ## Limits
222
+
223
+ - Solid Objects requires Ruby 3.3 or newer and Rails 7.1 or newer.
224
+ - Delivery is at least once, not exactly once. Write each operation so that it can run again.
225
+ - There are no transactions across actors. A change that must touch two events atomically needs one SQL transaction on normal tables.
226
+ - One busy event runs its calls one at a time. Many events can run at the same time.
227
+ - The gem is pre-1.0 and makes no production-ready claim.
228
+
229
+ ## More information
230
+
231
+ - [The example files](../../examples/guides/race_conditions/event_tickets.rb)
232
+ - [The tests for this guide](../../test/guides/race_conditions_test.rb)
233
+ - [Correctness and delivery semantics](../correctness.md)
234
+ - [Virtual actors in Ruby on Rails](../virtual-actors.md)
235
+ - [Expiring reservations](expiring-reservations.md)
236
+ - [Ordered jobs for each customer](ordered-jobs.md)
@@ -0,0 +1,156 @@
1
+ # Save state and queue work together in Rails
2
+
3
+ A database commit and a job enqueue are two separate steps. If the process stops between them, the database keeps the data, but the queue receives no work. The transactional outbox pattern writes the work into the same database transaction as the data. A separate process delivers the work later. A Solid Objects actor, from the `solid_objects` gem, commits its state, its database writes, and its staged effects in one transaction.
4
+
5
+ ## Reproduce the lost job
6
+
7
+ ```ruby
8
+ class Order < ApplicationRecord
9
+ def self.place_and_enqueue!(reference:, total_cents:)
10
+ order = create!(reference:, total_cents:)
11
+ ShipmentJob.perform_later(order_id: order.id)
12
+ order
13
+ end
14
+
15
+ def self.place_with_outbox!(reference:, total_cents:)
16
+ transaction do
17
+ order = create!(reference:, total_cents:)
18
+ OutboxMessage.create!(name: "request_shipment", arguments: { "order_id" => order.id })
19
+ order
20
+ end
21
+ end
22
+ end
23
+ ```
24
+
25
+ ```ruby
26
+ class ShipmentJob < ApplicationJob
27
+ def perform(order_id:)
28
+ order = Order.find(order_id)
29
+ ShippingProvider.create_shipment(idempotency_key: "order-#{order.id}", order_reference: order.reference)
30
+ end
31
+ end
32
+ ```
33
+
34
+ In `place_and_enqueue!`, `create!` commits the order. Then `perform_later` sends the job to the queue. The test uses a queue adapter that stops the process before the job reaches the queue. The order exists, but no job exists.
35
+
36
+ `after_commit` and `enqueue_after_transaction_commit` have the same gap: they enqueue the job after the database commit.
37
+
38
+ The Rails Guides state that `enqueue_after_transaction_commit` defers the enqueue until the Active Record transaction commits successfully. If the transaction rolls back, Rails does not enqueue the job. Rails 8 configures Solid Queue on a separate database by default. With this default, the job row and the order row use two databases. See [the Rails Guides, section 6.6.1](https://guides.rubyonrails.org/active_job_basics.html) (checked October 9, 2026).
39
+
40
+ [The transactional outbox tests](../../test/guides/transactional_outbox_test.rb) demonstrate the crash gap.
41
+
42
+ ## The plain outbox pattern
43
+
44
+ In `place_with_outbox!`, the model writes the order and an outbox row in one transaction.
45
+
46
+ ```ruby
47
+ class OutboxMessage < ApplicationRecord
48
+ JOBS = { "request_shipment" => ShipmentJob }.freeze
49
+
50
+ scope :pending, -> { where(delivered_at: nil).order(:id) }
51
+
52
+ def self.relay(limit: 100)
53
+ pending.limit(limit).each do |message|
54
+ JOBS.fetch(message.name).perform_later(**message.arguments.symbolize_keys)
55
+ message.update!(delivered_at: Time.current)
56
+ end
57
+ end
58
+ end
59
+ ```
60
+
61
+ The `relay` method uses these steps:
62
+
63
+ 1. It sends each undelivered row to the queue.
64
+ 2. It marks the row as delivered.
65
+
66
+ If the process stops after the enqueue and before the mark, the next relay sends the row again. The job must be idempotent. `ShipmentJob` passes `order-<id>` to the provider as the idempotency key.
67
+
68
+ Rails Event Store uses this pattern. Its scheduler writes the job into the same database table within the same transaction. A separate `res_outbox` process sends those rows to the background jobs tool. See [Rails Event Store](https://railseventstore.org/docs/advanced-topics/outbox) (checked October 9, 2026).
69
+
70
+ The plain outbox pattern is a good choice for an application that does not use actors.
71
+
72
+ ## The atomic boundary of an actor turn
73
+
74
+ ```ruby
75
+ class Checkout < SolidObjects::Actor
76
+ attribute :status, default: "open"
77
+ attribute :total_cents, default: 0
78
+ attribute :shipment_id, default: nil
79
+
80
+ def place(total_cents:)
81
+ return status unless status == "open"
82
+
83
+ self.status = "placed"
84
+ self.total_cents = total_cents
85
+ commit_action(:record_order, reference: actor_id, total_cents:)
86
+ emit(:request_shipment, order_reference: actor_id, on_success: :shipment_requested)
87
+ status
88
+ end
89
+
90
+ def shipment_requested(effect_id:, arguments:, result:)
91
+ self.status = "shipping"
92
+ self.shipment_id = result.fetch("shipment_id")
93
+ end
94
+ end
95
+ ```
96
+
97
+ ```ruby
98
+ SolidObjects.register_commit_action(:record_order) do |arguments, _context|
99
+ Order.create!(reference: arguments.fetch("reference"), total_cents: arguments.fetch("total_cents"))
100
+ end
101
+
102
+ SolidObjects.register_effect(:request_shipment) do |arguments, context|
103
+ ShippingProvider.create_shipment(
104
+ idempotency_key: context.id,
105
+ order_reference: arguments.fetch("order_reference")
106
+ )
107
+ end
108
+ ```
109
+
110
+ One successful turn commits the actor state, the staged effects, the same-database commit actions, the reminders, and the outbound messages together. Actor Ruby code and external I/O run outside the actor-state transaction.
111
+
112
+ - `commit_action(:record_order, ...)` writes the `orders` row inside that transaction. A commit action requires Solid Objects and `ActiveRecord::Base` to share one connection pool. It can run again after a database rollback. Keep each commit action deterministic, bounded, and database-only.
113
+ - `emit(:request_shipment, ...)` stages an effect row in the same transaction. After the commit, an effect worker calls the handler outside any database transaction.
114
+ - The handler passes `context.id` to the provider as the idempotency key. `context.id` is the effect ID. It stays the same on every attempt.
115
+ - `on_success: :shipment_requested` sends the provider result back to the actor as a normal message.
116
+ - If the turn raises, it commits no state, no order row, and no effect row.
117
+ - `place` returns early when the checkout is not open. A repeated call stages no additional order or effect.
118
+
119
+ ## What Solid Objects does not do
120
+
121
+ - Solid Objects does not wrap ordinary Active Record writes. Code outside an actor keeps its own transactions.
122
+ - A direct Active Record write inside an actor operation raises `SolidObjects::ApplicationWriteForbidden`. A registered commit action provides the only path for application row writes inside the actor commit.
123
+ - A commit action is unavailable when Solid Objects uses a separate database. Use `emit` with an idempotent effect consumer. Two databases cannot share one transaction.
124
+ - Solid Objects does not provide exactly-once delivery. An effect can run more than once.
125
+
126
+ ## What the tests prove
127
+
128
+ - A stop before the enqueue saves the order and loses the job.
129
+ - A failure between the order insert and the outbox insert saves neither row.
130
+ - The relay sends a message twice after a lost mark, and the provider creates one shipment.
131
+ - A failed turn keeps no state, no order row, and no effect row.
132
+ - A successful turn stores the state, the order row, and the effect row together.
133
+ - Repeated `place` calls stage one order and one effect in total.
134
+ - The provider response fails to reach the effect worker once. The effect runs again with the same `context.id`. The provider creates one shipment, and the actor records the shipment ID.
135
+
136
+ ## Run it in production
137
+
138
+ - Run `bundle exec solid_objects start`. Effects and their callbacks run only while this process runs. The SQL database keeps undelivered effects while the process does not run.
139
+ - Register effects and commit actions in an initializer at boot.
140
+ - The generated policies deny every call. Write a policy. Pass `authorization_context:` on each call. See [authorization policies](../authorization.md).
141
+ - See [effect recovery](../effect-recovery.md) for effects whose worker stopped during a call.
142
+
143
+ ## Limits
144
+
145
+ - Solid Objects requires Ruby 3.3 or newer and Rails 7.1 or newer.
146
+ - Delivery is at least once. Each effect handler must deduplicate with `context.id`.
147
+ - Solid Objects provides no transactions across actors.
148
+ - The gem is pre-1.0 and makes no production-ready claim.
149
+
150
+ ## More information
151
+
152
+ - [The example files](../../examples/guides/transactional_outbox/checkout.rb)
153
+ - [The tests for this guide](../../test/guides/transactional_outbox_test.rb)
154
+ - [Correctness and delivery semantics](../correctness.md)
155
+ - [Expiring reservations](expiring-reservations.md)
156
+ - [Prevent race conditions in Rails](race-conditions.md)
@@ -0,0 +1,81 @@
1
+ # rbs_inline: enabled
2
+
3
+ class SeatInventory < SolidObjects::Actor
4
+ HOLD_DURATION = 15.minutes
5
+ EXTENSION = 5.minutes
6
+ MAX_EXTENSIONS = 2
7
+
8
+ attribute :capacity, default: 0
9
+ attribute :holds, default: -> { {} }
10
+ attribute :confirmed, default: -> { {} }
11
+
12
+ query :seats_left do
13
+ seats_available
14
+ end
15
+
16
+ def open_show(capacity:)
17
+ self.capacity = capacity if self.capacity.zero?
18
+ seats_available
19
+ end
20
+
21
+ def hold(hold_id:, buyer:, seats:)
22
+ reject(:invalid_seats, "Hold at least one seat") unless seats.is_a?(Integer) && seats.positive?
23
+ return hold_result(hold_id) if active_hold?(hold_id)
24
+ return { status: "confirmed" } if confirmed.key?(hold_id)
25
+ reject(:not_enough_seats, "Only #{seats_available} seats are left") if seats > seats_available
26
+
27
+ deadline = HOLD_DURATION.from_now
28
+ self.holds = holds.merge(
29
+ hold_id => { "buyer" => buyer, "seats" => seats, "expires_at" => deadline.to_i, "extensions" => 0 }
30
+ )
31
+ schedule(at: deadline, key: hold_id).expire(hold_id:, expires_at: deadline.to_i)
32
+ hold_result(hold_id)
33
+ end
34
+
35
+ def extend_hold(hold_id:)
36
+ reject(:no_hold, "The hold expired or does not exist") unless active_hold?(hold_id)
37
+
38
+ hold = holds.fetch(hold_id)
39
+ reject(:extension_limit, "The hold cannot be extended again") if hold.fetch("extensions") >= MAX_EXTENSIONS
40
+
41
+ deadline = Time.at(hold.fetch("expires_at")) + EXTENSION
42
+ self.holds = holds.merge(
43
+ hold_id => hold.merge("expires_at" => deadline.to_i, "extensions" => hold.fetch("extensions") + 1)
44
+ )
45
+ schedule(at: deadline, key: hold_id).expire(hold_id:, expires_at: deadline.to_i)
46
+ hold_result(hold_id)
47
+ end
48
+
49
+ def confirm(hold_id:)
50
+ return { status: "confirmed" } if confirmed.key?(hold_id)
51
+ reject(:no_hold, "The hold expired or does not exist") unless active_hold?(hold_id)
52
+
53
+ hold = holds.fetch(hold_id)
54
+ self.holds = holds.except(hold_id)
55
+ self.confirmed = confirmed.merge(hold_id => hold.fetch("seats"))
56
+ unschedule(:expire, key: hold_id)
57
+ { status: "confirmed" }
58
+ end
59
+
60
+ def expire(hold_id:, expires_at:)
61
+ return seats_available unless holds.dig(hold_id, "expires_at") == expires_at
62
+
63
+ self.holds = holds.except(hold_id)
64
+ seats_available
65
+ end
66
+
67
+ private
68
+
69
+ def active_hold?(hold_id)
70
+ holds.key?(hold_id) && holds.dig(hold_id, "expires_at") > Time.current.to_i
71
+ end
72
+
73
+ def seats_available
74
+ held_seats = holds.each_key.select { |hold_id| active_hold?(hold_id) }.sum { |hold_id| holds.dig(hold_id, "seats") }
75
+ capacity - held_seats - confirmed.values.sum
76
+ end
77
+
78
+ def hold_result(hold_id)
79
+ { status: "held", expires_at: holds.dig(hold_id, "expires_at") }
80
+ end
81
+ end
@@ -0,0 +1,23 @@
1
+ # rbs_inline: enabled
2
+
3
+ class Account < ApplicationRecord
4
+ class InsufficientFunds < StandardError; end
5
+ class OutOfSequence < StandardError; end
6
+
7
+ def apply_entry!(kind:, amount_cents:)
8
+ change = (kind == "deposit") ? amount_cents : -amount_cents
9
+ raise InsufficientFunds, "balance #{balance_cents}, change #{change}" if balance_cents + change < 0
10
+
11
+ update!(balance_cents: balance_cents + change)
12
+ end
13
+
14
+ def apply_entry_in_sequence!(sequence:, kind:, amount_cents:)
15
+ with_lock do
16
+ raise OutOfSequence, "expected #{next_sequence}, received #{sequence}" if sequence > next_sequence
17
+ next if sequence < next_sequence
18
+
19
+ apply_entry!(kind:, amount_cents:)
20
+ update!(next_sequence: next_sequence + 1)
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,9 @@
1
+ # rbs_inline: enabled
2
+
3
+ class ApplyEntryJob < ApplicationJob
4
+ retry_on Account::OutOfSequence, wait: 5.seconds, attempts: 20
5
+
6
+ def perform(account_id:, sequence:, kind:, amount_cents:)
7
+ Account.find(account_id).apply_entry_in_sequence!(sequence:, kind:, amount_cents:)
8
+ end
9
+ end
@@ -0,0 +1,7 @@
1
+ # rbs_inline: enabled
2
+
3
+ class ApplyEntryUnorderedJob < ApplicationJob
4
+ def perform(account_id:, kind:, amount_cents:)
5
+ Account.find(account_id).apply_entry!(kind:, amount_cents:)
6
+ end
7
+ end
@@ -0,0 +1,14 @@
1
+ # rbs_inline: enabled
2
+
3
+ class CreateLedgerEntries < ActiveRecord::Migration[7.1]
4
+ def change
5
+ create_table :ledger_entries do |table|
6
+ table.string :account_id, null: false
7
+ table.string :entry_id, null: false
8
+ table.string :kind, null: false
9
+ table.integer :amount_cents, null: false
10
+ table.timestamps
11
+ end
12
+ add_index :ledger_entries, [ :account_id, :entry_id ], unique: true
13
+ end
14
+ end
@@ -0,0 +1,22 @@
1
+ # rbs_inline: enabled
2
+
3
+ class LedgerAccount < SolidObjects::Actor
4
+ attribute :balance_cents, default: 0
5
+ attribute :statement_balance_cents, default: nil
6
+
7
+ def apply(entry_id:, kind:, amount_cents:)
8
+ return balance_cents if LedgerEntry.exists?(account_id: actor_id, entry_id:)
9
+
10
+ change = (kind == "deposit") ? amount_cents : -amount_cents
11
+ reject(:insufficient_funds, "The balance is too low for this withdrawal") if balance_cents + change < 0
12
+
13
+ self.balance_cents += change
14
+ commit_action(:record_ledger_entry, account_id: actor_id, entry_id:, kind:, amount_cents:)
15
+ schedule(at: 1.day.from_now, key: "daily").close_statement
16
+ balance_cents
17
+ end
18
+
19
+ def close_statement
20
+ self.statement_balance_cents = balance_cents
21
+ end
22
+ end
@@ -0,0 +1,4 @@
1
+ # rbs_inline: enabled
2
+
3
+ class LedgerEntry < ApplicationRecord
4
+ end
@@ -0,0 +1,10 @@
1
+ # rbs_inline: enabled
2
+
3
+ SolidObjects.register_commit_action(:record_ledger_entry) do |arguments, _context|
4
+ LedgerEntry.create!(
5
+ account_id: arguments.fetch("account_id"),
6
+ entry_id: arguments.fetch("entry_id"),
7
+ kind: arguments.fetch("kind"),
8
+ amount_cents: arguments.fetch("amount_cents")
9
+ )
10
+ end
@@ -0,0 +1,15 @@
1
+ # rbs_inline: enabled
2
+
3
+ class Event < ApplicationRecord
4
+ def hold_seat_unsafely
5
+ return false if seats_available.zero?
6
+
7
+ update!(seats_available: seats_available - 1)
8
+ true
9
+ end
10
+
11
+ def hold_seat
12
+ self.class.where(id:).where("seats_available > 0")
13
+ .update_all("seats_available = seats_available - 1") == 1
14
+ end
15
+ end
@@ -0,0 +1,66 @@
1
+ # rbs_inline: enabled
2
+
3
+ class EventTickets < SolidObjects::Actor
4
+ HOLD_DURATION = 10.minutes
5
+
6
+ attribute :opened, default: false
7
+ attribute :seats_available, default: 0
8
+ attribute :holds, default: -> { {} }
9
+ attribute :sold, default: -> { [] }
10
+ attribute :title, default: ""
11
+ attribute :revision, default: 0
12
+
13
+ def open_sales(seats:)
14
+ return seats_available if opened
15
+
16
+ self.opened = true
17
+ self.seats_available = seats
18
+ end
19
+
20
+ def hold(buyer:, hold_id:)
21
+ release_expired_holds
22
+ return { held: true, hold_id: } if holds.dig(buyer, "hold_id") == hold_id
23
+ return { held: false, reason: "already_held" } if holds.key?(buyer)
24
+ return { held: false, reason: "sold_out" } if seats_available.zero?
25
+
26
+ deadline = HOLD_DURATION.from_now
27
+ self.seats_available -= 1
28
+ self.holds = holds.merge(buyer => { "hold_id" => hold_id, "expires_at" => deadline.to_i })
29
+ schedule(at: deadline, key: buyer).expire(buyer:, hold_id:, expires_at: deadline.to_i)
30
+ { held: true, hold_id: }
31
+ end
32
+
33
+ def confirm(buyer:, hold_id:)
34
+ return { confirmed: true } if sold.include?(hold_id)
35
+
36
+ release_expired_holds
37
+ reject(:no_hold, "The hold expired or does not exist") unless holds.dig(buyer, "hold_id") == hold_id
38
+
39
+ self.holds = holds.except(buyer)
40
+ self.sold = sold + [ hold_id ]
41
+ unschedule(:expire, key: buyer)
42
+ { confirmed: true }
43
+ end
44
+
45
+ def expire(buyer:, hold_id:, expires_at:)
46
+ return seats_available unless holds[buyer] == { "hold_id" => hold_id, "expires_at" => expires_at }
47
+
48
+ self.holds = holds.except(buyer)
49
+ self.seats_available += 1
50
+ end
51
+
52
+ def update_details(title:, base_revision:)
53
+ reject(:stale_revision, "Reload the event and try again") unless base_revision == revision
54
+
55
+ self.title = title
56
+ self.revision += 1
57
+ end
58
+
59
+ private
60
+
61
+ def release_expired_holds
62
+ expired_buyers = holds.select { |_buyer, hold| hold.fetch("expires_at") <= Time.current.to_i }.keys
63
+ self.holds = holds.except(*expired_buyers)
64
+ self.seats_available += expired_buyers.length
65
+ end
66
+ end
@@ -0,0 +1,22 @@
1
+ # rbs_inline: enabled
2
+
3
+ class Checkout < SolidObjects::Actor
4
+ attribute :status, default: "open"
5
+ attribute :total_cents, default: 0
6
+ attribute :shipment_id, default: nil
7
+
8
+ def place(total_cents:)
9
+ return status unless status == "open"
10
+
11
+ self.status = "placed"
12
+ self.total_cents = total_cents
13
+ commit_action(:record_order, reference: actor_id, total_cents:)
14
+ emit(:request_shipment, order_reference: actor_id, on_success: :shipment_requested)
15
+ status
16
+ end
17
+
18
+ def shipment_requested(effect_id:, arguments:, result:)
19
+ self.status = "shipping"
20
+ self.shipment_id = result.fetch("shipment_id")
21
+ end
22
+ end
@@ -0,0 +1,17 @@
1
+ # rbs_inline: enabled
2
+
3
+ class Order < ApplicationRecord
4
+ def self.place_and_enqueue!(reference:, total_cents:)
5
+ order = create!(reference:, total_cents:)
6
+ ShipmentJob.perform_later(order_id: order.id)
7
+ order
8
+ end
9
+
10
+ def self.place_with_outbox!(reference:, total_cents:)
11
+ transaction do
12
+ order = create!(reference:, total_cents:)
13
+ OutboxMessage.create!(name: "request_shipment", arguments: { "order_id" => order.id })
14
+ order
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,14 @@
1
+ # rbs_inline: enabled
2
+
3
+ class OutboxMessage < ApplicationRecord
4
+ JOBS = { "request_shipment" => ShipmentJob }.freeze
5
+
6
+ scope :pending, -> { where(delivered_at: nil).order(:id) }
7
+
8
+ def self.relay(limit: 100)
9
+ pending.limit(limit).each do |message|
10
+ JOBS.fetch(message.name).perform_later(**message.arguments.symbolize_keys)
11
+ message.update!(delivered_at: Time.current)
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,8 @@
1
+ # rbs_inline: enabled
2
+
3
+ class ShipmentJob < ApplicationJob
4
+ def perform(order_id:)
5
+ order = Order.find(order_id)
6
+ ShippingProvider.create_shipment(idempotency_key: "order-#{order.id}", order_reference: order.reference)
7
+ end
8
+ end
@@ -0,0 +1,12 @@
1
+ # rbs_inline: enabled
2
+
3
+ SolidObjects.register_commit_action(:record_order) do |arguments, _context|
4
+ Order.create!(reference: arguments.fetch("reference"), total_cents: arguments.fetch("total_cents"))
5
+ end
6
+
7
+ SolidObjects.register_effect(:request_shipment) do |arguments, context|
8
+ ShippingProvider.create_shipment(
9
+ idempotency_key: context.id,
10
+ order_reference: arguments.fetch("order_reference")
11
+ )
12
+ end
@@ -1,5 +1,5 @@
1
1
  # rbs_inline: enabled
2
2
 
3
3
  module SolidObjects
4
- VERSION = "0.17.2"
4
+ VERSION = "0.17.3"
5
5
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: solid_objects
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.17.2
4
+ version: 0.17.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Lucas Carlson
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-10-08 00:00:00.000000000 Z
11
+ date: 2026-10-09 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: actioncable
@@ -362,6 +362,10 @@ files:
362
362
  - docs/development.md
363
363
  - docs/effect-recovery.md
364
364
  - docs/fit.md
365
+ - docs/guides/expiring-reservations.md
366
+ - docs/guides/ordered-jobs.md
367
+ - docs/guides/race-conditions.md
368
+ - docs/guides/transactional-outbox.md
365
369
  - docs/implementation-plan.md
366
370
  - docs/local-testing.md
367
371
  - docs/migrating-existing-state.md
@@ -391,6 +395,21 @@ files:
391
395
  - examples/at_least_once/demo.rb
392
396
  - examples/at_least_once/effect_worker.rb
393
397
  - examples/at_least_once/sink.rb
398
+ - examples/guides/expiring_reservations/seat_inventory.rb
399
+ - examples/guides/ordered_jobs/account.rb
400
+ - examples/guides/ordered_jobs/apply_entry_job.rb
401
+ - examples/guides/ordered_jobs/apply_entry_unordered_job.rb
402
+ - examples/guides/ordered_jobs/create_ledger_entries.rb
403
+ - examples/guides/ordered_jobs/ledger_account.rb
404
+ - examples/guides/ordered_jobs/ledger_entry.rb
405
+ - examples/guides/ordered_jobs/solid_objects.rb
406
+ - examples/guides/race_conditions/event.rb
407
+ - examples/guides/race_conditions/event_tickets.rb
408
+ - examples/guides/transactional_outbox/checkout.rb
409
+ - examples/guides/transactional_outbox/order.rb
410
+ - examples/guides/transactional_outbox/outbox_message.rb
411
+ - examples/guides/transactional_outbox/shipment_job.rb
412
+ - examples/guides/transactional_outbox/solid_objects.rb
394
413
  - examples/quickstart/README.md
395
414
  - examples/quickstart/app/actors/ticket_sale.rb
396
415
  - examples/quickstart/smoke.rb