My shop runs on a dozen apps: why that hurts, and what one coherent system looks like
TL;DR
Difficulty: Intermediate
Each app in a shop keeps its own copy of part of the business, and copies drift.
- Stock, prices, customers and consent are where drift hurts: oversold items, disapproved Shopping ads, three versions of one customer, marketing to people who said no.
- Twelve tools at 99.9% each leave something broken about 8.7 hours a month.
- One application with one data model changes an order, its stock and its consent in one transaction, and tells the outside world through an outbox that never loses a message.
- Keep specialists for payments, email delivery and very large search, connected at one point in your own code.
- Move one job at a time, starting where drift costs most.
What to read first
Most online shops run on a platform plus a dozen apps, each with its own copy of the customers, the stock or the prices. This chapter works out what that costs for one invented homeware shop in Limerick, shows the code of the alternative (one Rails and Solidus application with transactions, an outbox and webhook endpoints you own), and says where a separate service is still the right call.
Twelve apps, twelve copies of your shop
Most online shops do not run on one system. They run on a platform plus a dozen apps: one for reviews, one for email, one for loyalty points, one for returns, one that keeps the warehouse in step, and a glue tool that joins the ones that do not talk to each other. Each app was a sensible decision on the day it was installed. Together they form something nobody designed.
This chapter answers one question: my shop runs on a dozen apps, why is that a problem, and what is the alternative? The short answer is that every app keeps its own copy of part of your shop, charges its own fee and fails on its own schedule. The copies drift apart, and the business pays for the drift in oversold stock, wrong prices in ads, emails to people who said no, and hours spent finding out which copy is right.
The alternative is one application with one data model: products, stock, orders, customers, consent and marketing events in one database, changed together inside transactions, and connected to the outside world through an interface you own. That is what a Ruby on Rails shop on Solidus gives you, and it is how I build shops. It is not the only sensible setup, and the last part of this chapter covers the jobs that should stay with a specialist service.
If you have not read it yet, the first chapter explains what a shop platform is made of and what renting one means. This one goes inside: how the data flows, where it breaks, and what the code looks like when it does not.
The example shop: Shannonside Home and its app stack
Every figure in this chapter is worked through for one invented shop. Shannonside Home (shannonsidehome.example) is an online homeware shop in Limerick. Niamh owns it and Callum is her developer. It sells ceramics, kitchen textiles, lamps and small furniture, about 1,400 products, ships across Ireland and to a few countries nearby, and takes card and PayPal.
Example: these are Shannonside Home's baseline figures for a typical month, all invented for this series. The shop has 110,000 sessions, a conversion rate of 1.8%, and so 1,980 orders at an average order value of €84 (including VAT, after discounts, excluding delivery). The gross margin on product is 52%, 9% of orders come back, and the newsletter has 38,000 subscribers. Ad spend is €16,500 a month. After VAT at 23%, refunds, cost of goods, payment fees (about 1.7%), fulfilment at €7.50 an order and returns handling at €10.50 a return, the contribution before marketing is €44,440 a month, which is €22.44 per order. The unit economics chapter builds that number step by step.
Shannonside runs on a rented platform with twelve apps and one glue tool. The fees below are invented for the example and are not the prices of any real product, but the shape is typical: a few large items and a long tail of small ones.
| App | What it does | Customer data it copies | Monthly fee (example) |
|---|---|---|---|
| Email marketing | Newsletter, abandoned basket and post purchase emails | Name, email, orders, consent | €360 |
| Stock sync | Keeps the Shannon warehouse and the shop in step | None, but every stock level | €175 |
| Returns portal | Return requests, labels, refunds | Name, address, orders | €150 |
| Loyalty points | Points per order, rewards | Name, email, orders | €115 |
| Shipping labels | Carrier labels and tracking | Name, address, phone | €69 |
| Search and filters | Site search and category filters | Search history | €57 |
| SMS | Delivery updates and offers | Name, phone, consent | €52 |
| Reviews | Review requests and display | Name, email, orders | €45 |
| Product feed | Feeds for Google and Meta | None, but every price | €45 |
| Accounting connector | Sends orders to the accounts | Name, address, orders | €35 |
| Back in stock alerts | Emails when a product returns | Email, wishes | €22 |
| Cookie banner | Consent for analytics and ads | Consent choices | €21 |
| Glue tool | Joins apps that have no direct link | Whatever passes through | €105 |
The total is €1,251 a month, or €15,012 a year. Divided by 1,980 orders that is , so €0.63 per order, about 2.8% of the €22.44 contribution per order. That looks small. The fees are not the problem. The problem is what the table's fourth column says: nine of the thirteen tools hold a copy of something about your customers, and two more hold a copy of every stock level or every price.
Why a dozen apps is a problem: copies, fees and failures
An app on a rented platform is a separate piece of software, run by a separate company, on its own servers. It reads data from your shop through the platform's interface (its API, the application programming interface), keeps what it needs in its own database, and does its job from there. The platform tells it about changes by sending webhooks: short messages to the app's address saying "an order was created" or "this product changed".
That design has three consequences, and every problem in this chapter comes from one of them.
- Each app has its own copy. The email tool has its own list of customers. The loyalty app has its own list of orders. The stock sync has its own idea of how many lamps are left. A copy is only as fresh as the last message that reached it.
- Each app has its own fee. Usually a monthly plan, often tiered by orders, contacts or features, and it rises as you grow.
- Each app has its own failure. It can be down while your shop is up, miss a message, hit a limit, or change how it works with an update you did not ask for.
None of this is a criticism of any one platform or app. It is what you get when a shop is assembled from parts that were built separately. Shopify, for example, is open about it in its own developer documentation, and its rules are sensible for a platform that hosts thousands of independent apps. The next sections go through what those rules mean for you.
What the platform's own documentation says about webhooks
Shopify's documentation for app developers says that webhooks can arrive more than once, that it "doesn't guarantee ordering within a topic, or across different topics for the same resource", and that an app "shouldn't rely on receiving data from Shopify webhooks"1. It recommends that apps run reconciliation jobs, which regularly fetch the data again to catch what was missed. If an app does not answer within five seconds, the delivery fails, Shopify retries "up to eight times in a four hour period", and if failures persist the subscription is removed2.
Apps also read through rate limits. On Shopify's GraphQL Admin API the limit is 100 cost points a second on the standard plans, 200 on Advanced, 1,000 on Shopify Plus and 2,000 for enterprise stores, and one query may not cost more than 1,000 points3. A sync that rereads a large catalogue has to pace itself.
And apps that touch personal data have to ask for it. Shopify calls this protected customer data: name, address, email and phone each have to be requested separately and approved, and the app has to meet requirements such as processing "only the minimum personal data required", applying retention periods and encrypting data at rest4. Those requirements exist because the apps keep copies.
Example: Shannonside's email tool is down for five hours on a Saturday, from 9am to 2pm. During that time 160 orders come in. The platform sends each order's webhook, gets no answer, and retries up to eight times over four hours. For the orders placed before 10am, the last retry falls before the tool is back, so those messages are gone. Assume orders arrive evenly at 32 an hour: the first hour's 32 orders never reach the email tool. Those 32 customers get no order follow up, no review request and no "complete the set" email, unless the tool runs its own reconciliation job or someone notices. Nobody sees an error anywhere. The orders exist in the platform, they just do not exist in one of the copies.
Every copy drifts: four places where the shop disagrees with itself
A copy is correct at the moment it is made and slowly wrong after that. How wrong depends on how often it is refreshed and how fast the original changes. In a shop, four kinds of data change fast enough to hurt: stock, prices, customers and consent.
Stock: selling the last lamp twice
Stock is the classic case. When a product sells through two routes that keep separate counts, for example the shop and a marketplace, or the shop and a showroom till, each route only learns about the other's sales when the stock sync runs. Between two syncs, both can sell the last unit.
The chance of that is a question about random arrivals. If orders on the other route arrive at an average rate per hour, the chance of at least one order there during a gap of hours follows from the Poisson distribution (Foundations: distributions):
Here is the chance that the last unit sells twice, is the average number of orders per hour for that product on the other route, is the sync delay in hours, and is the base of the natural logarithm. The formula assumes orders arrive independently of each other, which is close enough for one product.
The expected cost per month is then the number of times a product reaches its last unit, times that chance, times what one oversold order costs (Foundations: expected value):
where is the expected monthly cost, is the number of sell outs a month, is the chance from the first formula, and is the cost of handling one oversold order.
Example: Shannonside sells part of its range on a marketplace through a connector that syncs stock every 15 minutes, so . Across the products that sell there, the average rate near a sell out is 0.3 orders an hour, so and , a 7.2% chance per sell out. About 60 products reach their last unit each month, so the expected number of oversold orders is .
One oversold order of an oak side table at €280 costs Shannonside the payment fee that is not returned on a refund (, so €4.76), 25 minutes of Niamh's time at €28 an hour (€11.67), and a €10 apology voucher. That is . The expected monthly cost is , about €114 a month, before counting the customer who never comes back. If the connector only syncs once an hour, , the expected number becomes 15.6, and the cost about €412 a month.
Prices: the ad that shows last week's price
Prices live in the shop, but they are copied into the product feed for Google and Meta, into the email tool for product blocks, and sometimes into the search app. When a sale starts or ends, every copy has to follow. Google checks: if the price in your feed differs from the price on your product page, Google says "the product with the mismatch may be disapproved", and repeated problems "may lead to an account suspension"5. A disapproved product is hidden from Shopping ads and free listings until the mismatch is fixed. The Google Shopping chapter goes into the feed itself.
Example: Shannonside's autumn sale ends on Monday at 9am. The feed app refreshes once a day at 2am, so for 17 hours the feed still shows sale prices while the product pages show full prices. Google's crawler finds the mismatch, and 140 lamps and textiles are disapproved for two days. Assume Google Shopping brings Shannonside 300 orders a month, about 10 a day, and that the disapproved products account for the whole of those two days' Shopping orders. That is 20 orders lost, and at €22.44 contribution per order the cost is , so €448.80 for one sale ending, plus the account warning.
Customers: three versions of Hannah
Each app identifies customers in its own way, usually by email address. When a customer changes her address, uses a second email, or checks out as a guest and later creates an account, each copy handles it differently.
Example: Hannah orders as a guest with her work email in March, creates an account with her personal email in June, and moves house in September. The platform knows one account and one guest order. The email tool has two contacts. The loyalty app credits her points to the personal email only, so her March order earns nothing. The returns portal still holds the old address and sends the September return label to it. The SMS app has her phone number from the March order. Four tools, four versions of one person, and no single place that knows they are the same.
Consent: the "no" that only one tool heard
Consent is where drift turns into a legal problem. When someone unsubscribes, the law expects the "no" to apply everywhere you market to them, not only in the tool where they clicked it.
This is general information, not legal advice. Under the General Data Protection Regulation (GDPR), withdrawing consent must be "as easy" as giving it6, a controller who erases or corrects personal data must pass that on to each recipient it disclosed the data to, unless that is impossible or would take disproportionate effort7, and every service provider that processes personal data on your behalf needs a written contract that meets Article 288. For marketing by email and text, Ireland's ePrivacy Regulations (S.I. No. 336 of 2011) set the rules in regulation 13: an unsolicited marketing message to an individual needs their consent, with a narrow exception for existing customers who were given a simple way to refuse9. Every app on the list that holds customer data is, in the language of the law, a processor you are responsible for.
Platforms help here. Shopify, for example, requires every app in its App Store to handle deletion requests through mandatory compliance webhooks and to complete them "within 30 days"10. That is a good rule, and it also shows the shape of the problem: an erasure in your shop becomes a dozen erasures in a dozen databases, each done by someone else.
Example: in October, 190 of Shannonside's 38,000 subscribers unsubscribe from the newsletter. The email tool stops emailing them at once. The SMS app has its own consent field and is synced by hand at the start of each month, so on average an unsubscriber stays on the SMS list for about 15 days. During that window Shannonside sends one SMS offer, which reaches about half of them: roughly 95 people who said no. Each of those messages is a potential complaint to the Data Protection Commission (DPC), and none of them was intended.
Every app is a point of failure: the maths of a chain
A shop is only as reliable as the chain of things that must work for an order to be right. If each tool in the chain is up a high share of the time, the chain as a whole is up for less, because every link has to hold at once.
If the tools fail independently and each is available a share of the time, the chance that all of them are up at a given moment is (Foundations: probability):
where is the share of time every tool works, is the availability of tool , is the number of tools, and the last form applies when all tools have the same availability .
Example: each of Shannonside's 12 apps is available 99.9% of the time, which sounds excellent. The chance that all 12 are up is , so 98.81%. A month has about 730 hours, so some part of the stack is broken for hours a month. Not every failure stops orders, but in each of those hours something is quietly out of step: a review request not sent, a stock level not moved, a return label not created. With 16 tools it is 11.6 hours. With the one application and four outside services described later in this chapter, the chain that touches an order is much shorter.
The diagram below follows one order through the app model. The happy path works grand most of the time. The trouble is the other branch, which nobody watches.
Glue tools: paying per step to join what was never joined
When two apps have no direct connection, shops reach for a glue tool such as Zapier or Make. A glue tool watches for an event in one app and performs actions in others: "when an order is paid, add the customer to the loyalty app, tag them in the email tool, post to the team chat and add a row to a spreadsheet".
Glue tools are useful and quick to set up. Their cost model is worth understanding. Zapier, for example, counts "any successful action" as a task, so a Zap with two action steps that runs ten times uses 20 tasks, while triggers and failed steps do not count11. Once a plan reaches its task limit, Zapier either charges for extra tasks or holds new runs until the billing cycle resets, depending on the plan11. So the bill grows with orders, and a held run is another silent gap.
The larger cost is not on the invoice. A glue workflow is code that nobody calls code: it has no tests, no version history that a developer reviews, and it breaks when either app changes a field.
Example: Shannonside's glue tool runs one workflow per order with four action steps (loyalty, email tag, accounting note, spreadsheet row) and one per return with three. That is tasks for orders plus for returns, 8,454 tasks a month, and growing by four tasks for every extra order. On top, the workflows break about three times a month when an app updates, and each break takes Callum two hours to find and fix at €40 an hour: , so €240 a month of developer time that appears on no app invoice. That is more than twice the glue tool's own €105 fee.
The alternative: one application, one data model
The alternative is to run the shop as one application on one database. Every part of the business that changes together lives together: the catalogue, the stock, the orders, the customers, their consent and the marketing events. Features that used to be apps become parts of the application, reading and writing the same tables. Outside services remain where they are truly better (more on that later), and they are connected at one place in your code.
On Solidus, an open source eCommerce framework for Ruby on Rails, most of that data model already exists. A product is a Spree::Product, each buyable version of it (a size, a colour) is a Spree::Variant, and the stock of each variant in each warehouse is a Spree::StockItem at a Spree::StockLocation. An order is a Spree::Order with Spree::LineItem rows, Spree::Shipment and Spree::Payment records, and returns run through Spree::ReturnAuthorization and Spree::CustomerReturn. These live in tables such as spree_products, spree_orders and spree_stock_items in the shop's own PostgreSQL database. What Solidus does not include, you add as ordinary Rails models next to them: a consent record, a loyalty ledger, a review, a marketing event.
The point is not that one database is tidier. The point is that questions which used to need four exports and a spreadsheet become one query, and changes which used to need four tools to agree become one transaction.
Example: Niamh wants to pause promotional emails for 14 days for anyone who has just started a return, because an offer arriving while you wait for a refund reads badly. In the app model this needs the returns portal, the email tool and the glue tool to agree on who that is. In one database it is one query, which Callum runs every morning to build the pause list:
-- Customers with marketing consent who started a return in the last 14 days
SELECT DISTINCT o.email
FROM spree_orders o
JOIN spree_return_authorizations ra
ON ra.order_id = o.id
AND ra.state = 'authorized'
AND ra.created_at > now() - interval '14 days'
JOIN marketing_consents mc
ON mc.email = o.email
AND mc.channel = 'email'
AND mc.withdrawn_at IS NULL;
The first two tables come with Solidus. The third, marketing_consents, is Shannonside's own: one row per person, channel and consent, with the time it was given and the time it was withdrawn. With a 9% return rate, Shannonside has about returns a month, so about return authorisations in any 14 day window. If 60% of those customers have email consent, the pause list holds about 50 people on a typical morning. The newsletter goes to everyone else, and nobody had to copy anything anywhere.
The same consent table answers the SMS problem from earlier. There is one row per person and channel. The SMS sender and the email sender both read it at the moment they send, so a "no" given anywhere applies everywhere, at once. The unified campaign automation article goes deeper into consent as a field on the customer record, and the data warehouse article covers analysis across many sources once a shop outgrows one database for reporting.
Transactions: an order and its stock change succeed or fail together
A transaction is the database's promise that a group of changes happens completely or not at all. PostgreSQL's documentation puts it plainly: a transaction "bundles multiple steps into a single, all or nothing operation", the steps in between are not visible to other transactions running at the same time, and if an error stops it, "none of the steps affect the database at all"12.
For a shop, this is the difference between hoping and knowing. Creating an order, reducing stock and recording that the customer's newsletter consent came with the order are three changes. In the app model they happen in three systems at three different moments. In one application they can happen in one transaction: either the order exists and the stock went down and the consent is recorded, or none of it happened.
The second half of the promise is locking. When two customers try to buy the last unit at the same time, the database must let one check and reduce the stock before the other can look. Rails offers this as pessimistic locking: lock adds SELECT ... FOR UPDATE to a query, and with_lock locks a record you already have, both inside a transaction13.
Here is the shape of it in plain Rails. This is a simplified illustration of the principle with generic model names. Solidus has its own checkout with its own classes, shown after the code.
# app/services/place_order.rb
class PlaceOrder
class OutOfStock < StandardError; end
def initialize(cart)
@cart = cart
end
def call
ApplicationRecord.transaction do
order = Order.create!(customer: @cart.customer, total: @cart.total)
# Lock rows in a fixed order (by variant id) so two orders never wait on each other
@cart.items.sort_by(&:variant_id).each do |item|
stock = StockItem.lock.find_by!(variant_id: item.variant_id)
raise OutOfStock, item.variant_id if stock.count_on_hand < item.quantity
stock.update!(count_on_hand: stock.count_on_hand - item.quantity)
order.line_items.create!(variant_id: item.variant_id, quantity: item.quantity, price: item.price)
end
# The message for the outside world is written in the same transaction
OutboxMessage.create!(topic: "order.placed", payload: { order_id: order.id })
order
end
end
end
Read it from the top. ApplicationRecord.transaction opens the transaction. The order row is created. For each item, StockItem.lock.find_by! reads the stock row and locks it, so a second customer's request for the same product waits at this line until the first transaction finishes. If there is not enough stock, raising OutOfStock rolls everything back, including the order row that was already created. If there is, the stock goes down and the line item is written. The last step writes a message for the outside world into an outbox table, inside the same transaction, which the next section explains. Sorting the items by variant id means two baskets containing the same two products always lock them in the same order, which prevents the two transactions from each waiting for the other (a deadlock).
Solidus does the equivalent for you in its checkout. Before an order moves to complete, its state machine runs validate_line_item_availability and ensure_inventory_units, and after it the shipments are finalised14. Spree::Stock::InventoryUnitsFinalizer takes the stock off inside a database transaction, and every stock change goes through Spree::StockItem#adjust_count_on_hand, which wraps the change in with_lock14. What you add on top, such as a loyalty ledger or a consent record, can join those same transactions because it lives in the same database.
Example: on a Sunday evening, two customers both have Shannonside's last oak side table at €280 in their basket and press "place order" within the same second. With the lock, the first request reduces the stock from 1 to 0 and commits. The second request was waiting on the stock row, then reads 0, raises OutOfStock, and rolls back: no order, no payment captured, and the customer sees a clear "just sold out" message with similar tables. Without the lock and transaction, both orders go through, and the second one costs the €26.43 worked out earlier plus an unhappy customer. Over the 60 sell outs a month the oversell chance inside the shop itself drops to practically zero, because the check and the change are one step.
Telling the outside world: the outbox
A shop still has to tell other systems what happened: the email delivery service, the accounting software, the warehouse, the ad platforms. The trap is doing that inside the transaction. If the shop calls the email service and then the transaction rolls back, the customer gets a confirmation for an order that does not exist. If the shop commits and then crashes before calling, the order exists and nobody was told.
The transactional outbox pattern solves this. Chris Richardson describes it as storing the message in the database "as part of the transaction that updates the business entities", after which "a separate process then sends the messages"15. The message exists if and only if the order exists. A background job then delivers it, and keeps trying until the other side confirms.
# app/jobs/publish_outbox_job.rb
class PublishOutboxJob < ApplicationJob
queue_as :integrations
def perform
OutboxMessage.where(published_at: nil).order(:id).limit(100).each do |message|
Integrations.publish(message.topic, message.payload) # your own adapter per service
message.update!(published_at: Time.current)
end
end
end
# config/recurring.yml (Solid Queue, the default job backend in Rails 8)
production:
publish_outbox:
class: PublishOutboxJob
schedule: every minute
The job picks up to 100 unsent messages in the order they were written, hands each one to Integrations.publish (a small adapter you write for each outside service), and marks it as sent. If a service is down, publish raises an error, the message stays unsent, and the next run a minute later tries again. Solid Queue reads recurring tasks from config/recurring.yml, where each task names a job class and a schedule16. A message can be delivered twice if the job stops between sending and marking, so each receiving adapter sends a unique message id that the other side can use to ignore repeats. The background workers article covers queues, retries and idempotency in depth.
Solidus also publishes its own events on an event bus, Spree::Bus, built on the Omnes library. When an order is finalised it publishes :order_finalized, and the Solidus guides show how to subscribe to it17. The guides make an important distinction: subscribers are for things that happen because of the order, such as statistics or a confirmation message, never for logic that could stop the order from completing17.
# app/subscribers/shannonside/loyalty_subscriber.rb
module Shannonside
class LoyaltySubscriber
include Omnes::Subscriber
handle :order_finalized, with: :award_points, id: :shannonside_award_points
def award_points(event)
AwardLoyaltyPointsJob.perform_later(event.payload[:order].id)
end
end
end
# config/initializers/omnes.rb
Rails.application.config.to_prepare do
Shannonside::LoyaltySubscriber.new.subscribe_to(Spree::Bus)
end
The loyalty "app" is now 20 lines in the shop's own code base and one table. It sees every order, because it is told by the code that completes the order, not by a webhook that might not arrive.
Example: the same five hour Saturday outage as before, now at Shannonside's email delivery service. The 160 orders are placed normally, because the shop does not depend on the email service to take an order. Each order writes an outbox message. For five hours PublishOutboxJob runs every minute, fails on those messages, and leaves them unsent. At 2pm the service is back, and the next run sends the backlog in order, 100 at a time, within two minutes. Messages lost: zero. Compare that with the 32 lost in the app model, where the platform's retries ran out after four hours.
Integration in both directions, through an interface you own
Owning the application does not mean shutting the world out. It means the connections are yours: you decide what goes out, what comes in, in which format, and what happens when it fails. Integration runs in both directions.
Outwards, the outbox above sends events to any service, and the shop can offer its own API to others. Solidus has an API for products, orders and more, and a shop built "API first" can serve a mobile app or a partner from the same data. The headless and API first Solidus article covers that side.
Inwards, other systems send data to the shop: a warehouse reports stock counts, a carrier reports a delivery, a payment provider reports a refund. They usually do this with webhooks, the same mechanism as before, only now the shop is the receiver and you write the rules. A good receiving endpoint does four things: it checks that the message really comes from the sender, it stores the message before doing anything else, it ignores a message it has already seen, and it answers quickly and does the work afterwards.
# app/controllers/webhooks/warehouse_controller.rb
module Webhooks
class WarehouseController < ActionController::API
def create
body = request.raw_post
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, body)
given = request.headers["X-Warehouse-Signature"].to_s
return head :unauthorized unless ActiveSupport::SecurityUtils.secure_compare(expected, given)
event = JSON.parse(body)
InboundEvent.create!(source: "warehouse", external_id: event.fetch("id"), payload: event)
ApplyWarehouseEventJob.perform_later(event.fetch("id"))
head :accepted
rescue ActiveRecord::RecordNotUnique
head :ok # seen this message before, nothing to do
end
private
def secret
Rails.application.credentials.dig(:warehouse, :webhook_secret)
end
end
end
The warehouse signs each message with a secret you both know, using a keyed hash (HMAC). The controller computes the same hash over the raw body and compares the two with secure_compare, which takes the same time whether the first or the last character differs, so an attacker cannot guess the signature by timing18. A unique index on source and external_id in the inbound_events table makes a repeated message fail with RecordNotUnique, which the controller answers with a calm 200. The real work happens in a job:
# app/jobs/apply_warehouse_event_job.rb
class ApplyWarehouseEventJob < ApplicationJob
def perform(external_id)
event = InboundEvent.find_by!(source: "warehouse", external_id: external_id)
return if event.processed_at
variant = Spree::Variant.find_by!(sku: event.payload.fetch("sku"))
location = Spree::StockLocation.find_by!(code: "shannon")
stock_item = variant.stock_items.find_by!(stock_location: location)
stock_item.with_lock do
delta = event.payload.fetch("on_hand") - stock_item.count_on_hand
stock_item.stock_movements.create!(quantity: delta) unless delta.zero?
event.update!(processed_at: Time.current)
end
end
end
The job finds the variant by its stock keeping unit (SKU) and the Shannon stock location, locks the stock row, and records the difference as a Spree::StockMovement. Solidus applies every stock movement to the stock item's count14, and the movement stays as a row in the database, so every change to stock has a record explaining where it came from. Marking the event as processed happens inside the same lock, so a second run of the job does nothing. Messages that can arrive out of order, and time based checks, are covered in the webhooks and serverless article.
Example: Shannonside's warehouse in Shannon, Co. Clare, counts stock every evening and sends a correction for each SKU whose count changed, about 120 messages a night. Tonight it reports 14 of the blue linen tea towel where the shop shows 16, because two were found damaged. The endpoint verifies the signature, stores the message and answers in a few milliseconds. The job locks the stock row, computes , writes a stock movement of minus two with the event as its reason, and marks the event processed. When the warehouse resends the same message an hour later after a hiccup on its side, the unique index rejects it and nothing changes. Tomorrow, Niamh can see in the stock history exactly which movement took the count from 16 to 14, and why.
The cost of change in each model
The strongest argument for one application is not today's bill. It is what the next change costs. Shops change all the time: a new product type, a new delivery promise, a new market. In the app model, a change that crosses several apps needs each of them to support it, and some changes are limited by the platform itself. In one application, it is a change to your own code, built and tested like any other.
A concrete limit: on Shopify, checkout UI extensions that add your own content to the information, shipping and payment steps "are available only to stores on a Shopify Plus plan"19. On the other plans you can extend the thank you and order status pages, but not those middle steps of the checkout. That is a reasonable rule for a platform that has to keep every shop's checkout secure and upgradable. It also means that some changes to checkout cost a plan upgrade before they cost any development.
Example: Niamh wants to sell made to order oak furniture. Each piece has a lead time of six weeks, which must show on the product page, in the basket, in the checkout next to the delivery options, and in the confirmation email, and the order must go to the joiner in Ennis automatically.
In the app model on a standard plan this means: a product options app for the made to order flag (a new monthly fee), the lead time shown on the product page and in the basket through the theme, no lead time inside the checkout's shipping step without moving to Shopify Plus, a new template in the email tool that reads the flag from the platform's data, and a glue workflow that sends the joiner an email per order. That is five places, three companies' tools, and one plan limit.
In one application it means: a lead_time_days column on the variant, a line in the product page, basket and checkout views, a line in the confirmation mailer, and a new outbox topic order.made_to_order with an adapter that emails the joiner. Every part is in one code base, covered by the same tests, and released through the same test gate. As a rough illustration, a developer who knows the code base would plan two to four days for this, including tests. The point is not the exact number. It is that the work is all yours to plan, and nothing in it waits for another company's roadmap.
| Change | App model (example) | One application (example) |
|---|---|---|
| Lead time on product page and basket | Theme change plus an options app | View change, one column |
| Lead time in checkout delivery step | Needs Shopify Plus | View change |
| Lead time in confirmation email | New template in the email tool | One line in the mailer |
| Order to the joiner | Glue workflow, a task per order | One outbox topic and adapter |
| Tests | Spread across tools, mostly manual | One test suite, one release |
When a separate service is still right
One application does not mean building everything yourself. Some jobs are better done by a specialist, and pretending otherwise is its own kind of mistake. The test is simple: keep the data model and the business rules in your application, and use a separate service where the service brings something you cannot sensibly build, such as a certification, a reputation or a scale.
Payments. Card numbers are regulated by the Payment Card Industry Data Security Standard (PCI DSS). Stripe's integration guide notes that a business handling card data directly "might be required to meet more than 300 security controls", while its low risk integrations send card details straight to Stripe "without it passing through your servers, reducing your PCI obligations"20. So the shop keeps the payment record, the amount and a reference, and the provider keeps the card. The payment stack article goes into choosing and switching providers.
Email delivery. Writing and choosing emails belongs in your application, next to the data. Delivering them is a specialist job. Google requires senders of more than 5,000 messages a day to Gmail to authenticate their domain with the email authentication standards SPF, DKIM and DMARC, offer one click unsubscribe, and keep reported spam rates "below 0.30%"21. A delivery service keeps the infrastructure and reputation for that, and your outbox hands it finished messages. The email and SMS chapter covers the channel itself.
Search at scale. PostgreSQL has full text search built in, with stemming, ranking and indexes22, which is plenty for 1,400 products. A dedicated search engine earns its place when the catalogue runs to hundreds of thousands of items, or when typo tolerance, synonyms and merchandising rules become a daily job. Even then, the shop stays the source of truth and the search index is a copy it rebuilds. The site search chapter covers what good search does.
Accounting software and carrier networks follow the same rule: the specialist does the job, your application holds the record and owns the connection.
Example: Shannonside's twelve apps and one glue tool, sorted with that flow. Reviews, loyalty points, back in stock alerts, search and filters, the returns portal, the product feed, the stock sync logic, the cookie consent record and every glue workflow become parts of the one application. Card and PayPal payments go to a payment provider. Email and SMS sending go to one delivery service, with the content and the consent decided in the shop. Shipping labels go to the carriers' own APIs through one adapter. The accounts receive orders through one connector to the accounting software. Thirteen tools become one application and four outside services, and only one of those four (payments) sits in the path of taking an order.
Getting there without a big bang
Nobody has to replace twelve apps in one weekend. The safer route is to move one job at a time, so the old and the new run side by side until the new one is proven. Martin Fowler calls this the strangler fig approach: a new system grows around the edges of the old one and takes over piece by piece until the old one can be switched off23.
The order matters. Start where drift costs the most and the data is simplest, and leave the parts with the most history until the shop's own data model is settled. The migration article lists what moves with a shop and what does not, and who actually owns your business data covers getting your data out of each app.
Example: Shannonside's order of work, by cost of drift. First the consent record, because unsent "no"s are a legal risk and the data is small: one table, read by every sender. Second, stock and the warehouse connection, because oversells cost about €114 a month and grow with sell outs. Third, the product feed, because one price mismatch cost €448.80. Then loyalty, reviews and back in stock alerts, which are small features once the data lives in one place. The returns portal comes last, because it holds the most history and its process touches the warehouse, the carriers and refunds. At each step the old app stays on until the new part has run alongside it for a full month without a difference.
Conclusion: one record, many hands
A dozen apps is not a mistake anyone made on purpose. It is what happens when each need is solved on the day it appears. The cost shows up later and quietly: copies that drift, failures that multiply, glue that breaks, and changes that need five companies to agree.
One application with one data model turns that around. Stock, prices, customers and consent live in one place and change inside transactions. The outside world hears about it through an outbox that never loses a message, and talks back through endpoints you control. Specialists still handle payments, email delivery and very large search, connected at one point in your code. The shop becomes one record with many hands, instead of many records with no head.
The next chapter shows what that one application can then do on its own: automating stock, fulfilment, returns and customer service on Rails. And because every process runs in your own code, every process can also be measured, which is where the chapter on measuring features in isolation picks up.