Payments are experiencing issues due to temporary restrictions in Russia. If your payment does not go through, please submit a support request.Our support team is available 24/7 — we are always here to help with hosting and server issues.We are now accepting requests for dedicated server rental and colocation services in our data center.Reminder: we recommend enabling backups for additional data protection.A new VPS/VDS lineup with NVMe storage and improved performance is now available.Maintenance work on some servers has been completed. All services are operating normally.
Article11 min readViews2

Delivery not created, but the item is already reserved: checking compensation

A deterministic model shows how to release a reservation after a downstream API failure, survive a timeout on an already-executed compensation, and retry it without double-refunding the balance.

Comments 0

A blue container on a curved return chute near a rack, next to a closed coral delivery zone
In this article

If a product reserve is already created and the next service rejects delivery, a local rollback will not undo the state change in the external system. A reliable approach is to save the list of completed steps and execute a separate idempotent command to release the reserve. If the result is unknown, the state remains compensation_pending: the same request is retried until confirmation or handed over for manual resolution. The status compensated appears only after confirmed release.

In a small example, an order reserves one unit of an item, then attempts to create a delivery. The model checks the normal path, delivery failure, a timeout on an already-executed release, and unavailability of the compensation service. The last two cases are critical: the word "rollback" sounds upbeat, but a remote system sometimes cannot read the presentation.

Why a standard rollback is insufficient

A 1C-Bitrix database transaction can only revert changes within its own committed boundary. Reservations in an external accounting system, delivery tasks, or payments reside in a different store. After a successful remote call, a local exception cannot roll back the foreign system in time.

The documented compensating transaction pattern suggests recording successfully completed steps and defining corresponding rollback actions. Compensation must account for business rules and concurrent changes; it does not need to literally restore the original bytes. Since its own failure is also possible, progress must be persisted and repeated commands made idempotent.

A Saga breaks a distributed business operation into local transactions and triggers compensating actions after a subsequent step fails. AWS Documentation explicitly distinguishes between proceeding forward and rolling back: a transient failure is sometimes better to retry, while an irreversible action should not be masked by the word "cancel".

Conditions for a safe model

  • Environment: CPython 3.12.14, standard library only.
  • All data resides in the process memory; no network, files, database, working store, or real APIs are used.
  • The initial stock equals five units; each scenario uses a new object and reserves one unit.
  • The order ID serves as the key for reservation and subsequent release; the quantity is stored in the same workflow object and does not change between attempts.
  • Artificial modes separately model failure before the effect and timeout after the actual release.
  • The program writes nothing and deletes nothing; there is nothing to clean up after completion.

Full reproducible example

from __future__ import annotations from dataclasses import dataclass, field class DeliveryError(RuntimeError): pass class CompensationUnavailable(RuntimeError): pass class CompensationResultUnknown(TimeoutError): pass @dataclass class Inventory: available: int = 5 reservations: dict[str, str] = field(default_factory=dict) def reserve(self, order_id: str, quantity: int) -> str: if quantity <= 0: raise ValueError("quantity must be positive") previous = self.reservations.get(order_id) if previous == "active": return "already_reserved" if previous == "released": raise ValueError("released reservation cannot be reused") if self.available < quantity: raise ValueError("insufficient_stock") self.available -= quantity self.reservations[order_id] = "active" return "reserved" def release( self, order_id: str, quantity: int, *, mode: str = "ok", ) -> str: if mode == "fail_before_effect": raise CompensationUnavailable("inventory_api_unavailable") current = self.reservations.get(order_id) if current == "released": return "already_released" if current != "active": raise ValueError("active_reservation_not_found") self.available += quantity self.reservations[order_id] = "released" if mode == "effect_then_timeout": raise CompensationResultUnknown("release_result_unknown") if mode != "ok": raise ValueError("unknown release mode") return "released" @dataclass class Delivery: created: set[str] = field(default_factory=set) def create(self, order_id: str, *, fail: bool = False) -> str: if fail: raise DeliveryError("delivery_rejected") if order_id in self.created: return "already_created" self.created.add(order_id) return "created" @dataclass class Workflow: order_id: str quantity: int state: str = "new" completed_steps: list[str] = field(default_factory=list) compensation_attempts: int = 0 def compensate_inventory( workflow: Workflow, inventory: Inventory, *, mode: str = "ok", ) -> str: workflow.compensation_attempts += 1 try: result = inventory.release( workflow.order_id, workflow.quantity, mode=mode, ) except (CompensationUnavailable, CompensationResultUnknown): workflow.state = "compensation_pending" return "pending" workflow.state = "compensated" return result def run_order( workflow: Workflow, inventory: Inventory, delivery: Delivery, *, delivery_fails: bool, compensation_mode: str = "ok", ) -> None: inventory.reserve(workflow.order_id, workflow.quantity) workflow.completed_steps.append("inventory_reserved") try: delivery.create(workflow.order_id, fail=delivery_fails) except DeliveryError: compensate_inventory( workflow, inventory, mode=compensation_mode, ) return workflow.completed_steps.append("delivery_created") workflow.state = "completed" def scenario_success() -> None: inventory = Inventory() delivery = Delivery() workflow = Workflow("order-success", 1) run_order( workflow, inventory, delivery, delivery_fails=False, ) assert workflow.state == "completed" assert inventory.available == 4 assert inventory.reservations[workflow.order_id] == "active" assert workflow.order_id in delivery.created print( "success: state=completed available=4 " "reservation=active delivery=created" ) def scenario_delivery_failure() -> None: inventory = Inventory() delivery = Delivery() workflow = Workflow("order-rejected", 1) run_order( workflow, inventory, delivery, delivery_fails=True, ) assert workflow.state == "compensated" assert inventory.available == 5 assert inventory.reservations[workflow.order_id] == "released" assert not delivery.created print( "delivery_failure: state=compensated available=5 " "reservation=released" ) def scenario_unknown_release_result() -> None: inventory = Inventory() delivery = Delivery() workflow = Workflow("order-timeout", 1) run_order( workflow, inventory, delivery, delivery_fails=True, compensation_mode="effect_then_timeout", ) assert workflow.state == "compensation_pending" assert inventory.available == 5 assert inventory.reservations[workflow.order_id] == "released" retry_result = compensate_inventory(workflow, inventory) assert retry_result == "already_released" assert workflow.state == "compensated" assert workflow.compensation_attempts == 2 assert inventory.available == 5 print( "unknown_release_result: first=pending retry=already_released " "state=compensated attempts=2 available=5" ) def scenario_compensation_outage() -> None: inventory = Inventory() delivery = Delivery() workflow = Workflow("order-outage", 1) run_order( workflow, inventory, delivery, delivery_fails=True, compensation_mode="fail_before_effect", ) assert workflow.state == "compensation_pending" assert inventory.available == 4 assert inventory.reservations[workflow.order_id] == "active" retry_result = compensate_inventory(workflow, inventory) assert retry_result == "released" assert workflow.state == "compensated" assert workflow.compensation_attempts == 2 assert inventory.available == 5 print( "compensation_outage: first=pending retry=released " "state=compensated attempts=2 available=5" ) def main() -> None: scenario_success() scenario_delivery_failure() scenario_unknown_release_result() scenario_compensation_outage() if __name__ == "__main__": main()

Save the code in a new empty directory as saga_compensation_lab.py and run:

python3 saga_compensation_lab.py

Two sequential runs completed with exit code 0 and produced identical output:

success: state=completed available=4 reservation=active delivery=created delivery_failure: state=compensated available=5 reservation=released unknown_release_result: first=pending retry=already_released state=compensated attempts=2 available=5 compensation_outage: first=pending retry=released state=compensated attempts=2 available=5

SHA-256 of the verified file: 5f05a86548c7372a8fbb3bc2336221f4c891a47390203f7614a4c3ef37f59bba.

This confirms the run

  • On success of the chain, the reservation remains active and the delivery is created; subsequent deductions or shipments are intentionally not included in this model.
  • On an explicit delivery failure, the release returns the balance from four to five and transitions the workflow to compensated.
  • On a timeout after the effect, the orchestrator first leaves the state as compensation_pending. A retry with the same order_id receives already_released and does not increment the unit count a second time.
  • If the service is unavailable before the effect, the reservation remains active and visible as an incomplete compensation. The next attempt releases it and only then completes the workflow.

The model demonstrates branching and the balance invariant in isolated memory. It does not measure network performance, does not test the API of a specific delivery service, and does not show implementation in a real project. In a real integration, concurrent modification of the reservation may require object versioning, state checks, or manual resolution.

A release timeout is not yet a failure

If the client does not receive a response, it knows only the result of the wait. The external system might not have accepted the command, executed it fully, or completed it later. Therefore, after a timeout, one must not silently return the balance by a local addition: if the release was already performed, this results in a double return.

The retry uses the same stable operation key. The already_released response in the model is considered confirmation of the final state, not a new compensation. If the API does not support idempotent release, a separate request for the current state and a rule for handling discrepancies are required.

How to migrate the mechanism into the store integration

  • Describe one business operation and its boundaries: order creation, product reservation, delivery, payment, or transfer to 1C. Do not combine actions with different cancellation rules into a single workflow.
  • For each step, record the stable operation_id, input data, confirmed result, and allowable compensating action.
  • Distinguish between an explicit business failure, a temporary technical glitch, and an unknown result after a timeout. They require different next steps.
  • Store compensation_pending persistently so that restarting the process does not lose an incomplete release.
  • Make compensation idempotent and test three scenarios: retrying a command after the effect has already occurred, command failure before any effect, and prolonged unavailability of the external system.
  • Assign a point of no return. A completed payment, a legally significant document generated, or cargo already handed to a carrier may require a separate procedure rather than an automatic reverse callback.
  • In the log, store identifiers, states, attempts, and reasons without tokens, personal data, or full responses from external systems.

For the user module '1C-Bitrix: Site Management', before implementation, verify the product edition and version, exchange direction, product or product variant, reserve and stock fields, technical user permissions, workflow storage location, and external API contract. The educational model does not assert the presence of a standard Saga mechanism in a specific edition.

Boundary with adjacent mechanisms

Transactional outbox reliably persists a local change and an outgoing event in a single database, but by itself does not undo an already executed remote reservation. Receiver idempotency does not determine which rollback business action is permissible. These mechanisms complement compensation rather than replace it.

Acceptance criteria

On the test environment, every confirmed direct step must have a saved state and an explicitly allowed next move. After delivery failure, the reserve is either confirmed as released or remains in compensation_pending with the ability to safely retry and manually resolve. Retrying a command does not change the stock a second time, and an unknown result is not reported as a successful cancellation.

Discussion 0

Share your experience and ask questions. Comments without links appear after editorial review.

No comments yet. Start the discussion.