Composable Commerce
Overview
Composable commerce is an architectural approach based on MACH principles — Microservices, API-first, Cloud-native, Headless — where each commerce capability (cart, catalog, search, CMS, checkout, loyalty) is provided by a best-of-breed service rather than a monolithic platform. Services communicate via APIs and events, enabling teams to replace or upgrade individual capabilities without touching the rest of the system. This skill covers MACH architecture patterns, service integration, event-driven coordination, and the operational considerations of running a composable stack in production.
When to Use This Skill
- When a monolithic platform (Magento, Salesforce CC) can no longer scale with your team or traffic patterns
- When different domains (catalog, checkout, loyalty) have divergent release cadences and ownership
- When you need to mix best-of-breed vendors — e.g., Algolia for search, Contentful for CMS, commercetools for commerce
- When entering new markets requiring different fulfillment, pricing, or tax providers per region
- When building a platform that must support multiple storefronts (web, mobile, in-store, B2B portal) from a single backend
Prerequisites & Platform Notes
This skill is written for custom/headless storefronts (Node.js, Python, or similar backend). The code examples use TypeScript/Node.js and can be adapted to any stack.
Shopify: Shopify Hydrogen is Shopify's headless framework. MACH/composable patterns apply when using Shopify as the commerce backend with a custom frontend, or when mixing Shopify with other best-of-breed services.
WooCommerce: WooCommerce can serve as a headless backend via its REST API and WPGraphQL. These patterns apply when decoupling the frontend from WordPress.
Magento: Magento's GraphQL API and PWA Studio support headless architectures. These composable patterns apply to Magento as a backend service in a MACH stack.
You'll need:
- Node.js 18+ (or adapt to your backend language)
- PostgreSQL (or your preferred relational database)
- A search service (Algolia, Elasticsearch, or Typesense)
- Stripe account and API keys
- An email sending service (SendGrid, AWS SES, or Postmark)
Core Instructions
Design service boundaries around commerce capabilities
A typical composable commerce stack separates capabilities into discrete services:
| Capability |
Example Services |
| Product Catalog |
commercetools, Akeneo PIM, Salsify |
| Search & Discovery |
Algolia, Elasticsearch, Constructor.io |
| CMS / Content |
Contentful, Sanity, Storyblok |
| Cart & Checkout |
commercetools, Elastic Path, Medusa |
| Payments |
Stripe, Adyen, Braintree |
| Tax |
Avalara, TaxJar |
| Shipping & Fulfillment |
EasyPost, ShipBob, custom OMS |
| Customer Identity |
Auth0, Okta, Cognito |
| Loyalty & Promotions |
Talon.One, Voucherify |
| Email / Notifications |
SendGrid, Customer.io |
Define bounded contexts: each service owns its data and exposes it only via APIs. Never share databases between services.
Implement an API composition layer (BFF)
A Backend-for-Frontend (BFF) aggregates multiple upstream APIs into a single request, tailored to what the frontend needs:
// bff/src/routes/product-page.ts
import {getProduct} from '../services/catalog';
import {getSearchReviews} from '../services/reviews';
import {getRecommendations} from '../services/recommendations';
import {getInventory} from '../services/inventory';
export async function productPageData(productId: string, customerId?: string) {
// Parallel fetch from independent services
const [product, inventory, recommendations] = await Promise.all([
getProduct(productId),
getInventory(productId),
getRecommendations(productId, customerId),
]);
// Sequential: reviews needs product.sku
const reviews = await getSearchReviews(product.sku);
return {
product,
inventory,
recommendations,
reviews,
};
}
Expose the BFF as a GraphQL API using schema stitching or federation:
import {buildHTTPExecutor} from '@graphql-tools/executor-http';
import {stitchSchemas} from '@graphql-tools/stitch';
const gatewaySchema = await stitchSchemas({
subschemas: [
{ schema: await introspectSchema(catalogExecutor), executor: catalogExecutor },
{ schema: await introspectSchema(inventoryExecutor), executor: inventoryExecutor },
{ schema: await introspectSchema(reviewsExecutor), executor: reviewsExecutor },
],
});
Use event-driven architecture for cross-service coordination
Services should communicate asynchronously for workflows that span multiple capabilities (order placed → inventory reserved → fulfillment triggered → email sent):
// Order service publishes an event after checkout
import {EventBridge} from '@aws-sdk/client-eventbridge';
const eventBridge = new EventBridge({region: 'us-east-1'});
async function publishOrderPlaced(order: Order) {
await eventBridge.putEvents({
Entries: [
{
Source: 'commerce.orders',
DetailType: 'OrderPlaced',
Detail: JSON.stringify({
orderId: order.id,
customerId: order.customerId,
lineItems: order.lineItems,
totalAmount: order.totalAmount,
currency: order.currency,
}),
EventBusName: 'commerce-events',
},
],
});
}
// Inventory service subscribes and reserves stock
// EventBridge rule routes OrderPlaced → Lambda → inventory-service
export async function handler(event: EventBridgeEvent<'OrderPlaced', OrderPayload>) {
const {orderId, lineItems} = event.detail;
await reserveInventory(lineItems);
await publishInventoryReserved(orderId);
}
Implement the Saga pattern for distributed transactions
When a multi-step workflow must be atomic across services, use orchestrated sagas with compensating transactions:
// Choreography-based saga for order fulfillment
// Each service publishes events and reacts to others
// Order Service
on('CheckoutCompleted', async ({orderId, paymentIntentId}) => {
await orders.create({orderId, status: 'pending_payment'});
await publish('OrderCreated', {orderId, paymentIntentId});
});
// Payment Service
on('OrderCreated', async ({orderId, paymentIntentId}) => {
try {
await capturePayment(paymentIntentId);
await publish('PaymentCaptured', {orderId});
} catch (err) {
await publish('PaymentFailed', {orderId, reason: err.message});
}
});
// Fulfillment Service
on('PaymentCaptured', async ({orderId}) => {
await fulfillment.schedule(orderId);
});
// Order Service — compensate on failure
on('PaymentFailed', async ({orderId}) => {
await orders.update(orderId, {status: 'payment_failed'});
await releaseInventory(orderId);
await notifyCustomer(orderId, 'payment_failed');
});
Manage API versioning and backward compatibility
In a composable stack, services evolve independently. Use additive versioning strategies:
// Use content negotiation or URL versioning
// GET /api/v2/products/:id
// Accept: application/vnd.commerce.product.v2+json
// Apply the Tolerant Reader pattern — ignore unknown fields
interface ProductV1 {
id: string;
name: string;
price: number;
}
// V2 adds fields — existing consumers still work
interface ProductV2 extends ProductV1 {
categories?: string[];
attributes?: Record<string, string>;
brand?: string;
}
// Use feature flags to roll out breaking changes
async function getProduct(id: string, apiVersion: '1' | '2' = '1') {
const product = await catalog.findById(id);
return apiVersion === '2' ? toProductV2(product) : toProductV1(product);
}
Implement circuit breakers for resilience
When one service degrades, prevent cascading failures across the entire stack:
import CircuitBreaker from 'opossum';
const inventoryCircuit = new CircuitBreaker(checkInventory, {
timeout: 3000, // Request timeout in ms
errorThresholdPercentage: 50, // Open circuit if 50% of requests fail
resetTimeout: 30000, // Try again after 30 seconds
});
inventoryCircuit.fallback(() => ({
available: true, // Optimistic fallback — show as available
quantity: null, // Don't show exact quantity
}));
inventoryCircuit.on('open', () => {
logger.warn('Inventory service circuit OPEN — using fallback');
metrics.increment('circuit_breaker.inventory.open');
});
// Usage
const stock = await inventoryCircuit.fire(productId);
Examples
commercetools SDK integration for catalog
import {createApiBuilderFromCtpClient} from '@commercetools/platform-sdk';
import {ClientBuilder} from '@commercetools/sdk-client-v2';
const ctpClient = new ClientBuilder()
.withProjectKey(process.env.CTP_PROJECT_KEY!)
.withClientCredentialsFlow({
host: 'https://auth.us-central1.gcp.commercetools.com',
projectKey: process.env.CTP_PROJECT_KEY!,
credentials: {
clientId: process.env.CTP_CLIENT_ID!,
clientSecret: process.env.CTP_CLIENT_SECRET!,
},
scopes: ['manage_project:' + process.env.CTP_PROJECT_KEY],
fetch,
})
.withHttpMiddleware({host: 'https://api.us-central1.gcp.commercetools.com', fetch})
.build();
const apiRoot = createApiBuilderFromCtpClient(ctpClient).withProjectKey({
projectKey: process.env.CTP_PROJECT_KEY!,
});
// Fetch product by slug
const product = await apiRoot
.products()
.get({queryArgs: {where: `slug(en="${slug}")`, expand: ['productType']}})
.execute();
Algolia search with Contentful CMS enrichment
import algoliasearch from 'algoliasearch';
import {createClient as createContentfulClient} from 'contentful';
const algolia = algoliasearch(process.env.ALGOLIA_APP_ID!, process.env.ALGOLIA_SEARCH_KEY!);
const contentful = createContentfulClient({space: process.env.CONTENTFUL_SPACE_ID!, accessToken: process.env.CONTENTFUL_TOKEN!});
async function searchProducts(query: string, filters?: string) {
// Search in Algolia for product IDs and structured data
const {hits} = await algolia.initIndex('products').search<AlgoliaProduct>(query, {
filters,
attributesToRetrieve: ['objectID', 'name', 'price', 'contentfulEntryId'],
});
// Enrich with rich content from Contentful
const contentEntryIds = hits.map(h => h.contentfulEntryId).filter(Boolean);
const contentEntries = await contentful.getEntries({
content_type: 'productPage',
'sys.id[in]': contentEntryIds.join(','),
});
const contentMap = new Map(contentEntries.items.map(e => [e.sys.id, e]));
return hits.map(hit => ({
...hit,
content: contentMap.get(hit.contentfulEntryId),
}));
}
Best Practices
- Define a clear data ownership model — each piece of data has exactly one system of record; other services read from it via API, never write to it directly
- Design for eventual consistency — cross-service data will be temporarily inconsistent after an event; build UIs and workflows that tolerate this (e.g., optimistic inventory, compensating transactions)
- Use an API gateway for cross-cutting concerns — authentication, rate limiting, request logging, and SSL termination belong at the gateway, not in every service
- Implement distributed tracing — use OpenTelemetry with a trace ID propagated across all service calls; this is essential for debugging multi-service request failures
- Version your events — event schemas change over time; include a
schemaVersion field in every event payload and maintain backward-compatible consumers
- Use a service mesh for service-to-service traffic — tools like Istio or AWS App Mesh handle mutual TLS, load balancing, and retries at the infrastructure layer
- Start with a modular monolith — decompose into microservices only when you have clear team ownership boundaries and operational maturity; premature decomposition creates accidental complexity
Common Pitfalls
| Problem |
Solution |
| Distributed transaction failures leave data inconsistent |
Implement sagas with compensating transactions; use outbox pattern to guarantee event publication after DB write |
| Service latency compounds in the critical path |
Move non-critical services off the critical path using async events; set aggressive timeouts and circuit breakers on all external calls |
| API contract breaks downstream consumers |
Use consumer-driven contract testing (Pact) so breaking changes are caught before deployment |
| Shared database creates hidden coupling |
Enforce the rule: one service, one schema; use event sourcing or change data capture for cross-service data propagation |
| Debugging failures across 10 services |
Implement distributed tracing with OpenTelemetry from day one; correlate logs with a single trace ID per user request |
Related Skills
- @commerce-api-gateway
- @saleor-development
- @shopify-hydrogen
- @webhook-architecture
- @flash-sale-scaling
- @edge-commerce
1---2name: composable-commerce3description: Architect a modern store using MACH principles — independent microservices, API-first integrations, cloud-native hosting, and headless frontend4---56# Composable Commerce78## Overview910Composable commerce is an architectural approach based on MACH principles — Microservices, API-first, Cloud-native, Headless — where each commerce capability (cart, catalog, search, CMS, checkout, loyalty) is provided by a best-of-breed service rather than a monolithic platform. Services communicate via APIs and events, enabling teams to replace or upgrade individual capabilities without touching the rest of the system. This skill covers MACH architecture patterns, service integration, event-driven coordination, and the operational considerations of running a composable stack in production.1112## When to Use This Skill1314- When a monolithic platform (Magento, Salesforce CC) can no longer scale with your team or traffic patterns15- When different domains (catalog, checkout, loyalty) have divergent release cadences and ownership16- When you need to mix best-of-breed vendors — e.g., Algolia for search, Contentful for CMS, commercetools for commerce17- When entering new markets requiring different fulfillment, pricing, or tax providers per region18- When building a platform that must support multiple storefronts (web, mobile, in-store, B2B portal) from a single backend1920## Prerequisites & Platform Notes2122**This skill is written for custom/headless storefronts** (Node.js, Python, or similar backend). The code examples use TypeScript/Node.js and can be adapted to any stack.2324**Shopify**: Shopify Hydrogen is Shopify's headless framework. MACH/composable patterns apply when using Shopify as the commerce backend with a custom frontend, or when mixing Shopify with other best-of-breed services.25**WooCommerce**: WooCommerce can serve as a headless backend via its REST API and WPGraphQL. These patterns apply when decoupling the frontend from WordPress.26**Magento**: Magento's GraphQL API and PWA Studio support headless architectures. These composable patterns apply to Magento as a backend service in a MACH stack.2728**You'll need**:29- Node.js 18+ (or adapt to your backend language)30- PostgreSQL (or your preferred relational database)31- A search service (Algolia, Elasticsearch, or Typesense)32- Stripe account and API keys33- An email sending service (SendGrid, AWS SES, or Postmark)3435## Core Instructions36371. **Design service boundaries around commerce capabilities**3839 A typical composable commerce stack separates capabilities into discrete services:4041 | Capability | Example Services |42 |-----------|-----------------|43 | Product Catalog | commercetools, Akeneo PIM, Salsify |44 | Search & Discovery | Algolia, Elasticsearch, Constructor.io |45 | CMS / Content | Contentful, Sanity, Storyblok |46 | Cart & Checkout | commercetools, Elastic Path, Medusa |47 | Payments | Stripe, Adyen, Braintree |48 | Tax | Avalara, TaxJar |49 | Shipping & Fulfillment | EasyPost, ShipBob, custom OMS |50 | Customer Identity | Auth0, Okta, Cognito |51 | Loyalty & Promotions | Talon.One, Voucherify |52 | Email / Notifications | SendGrid, Customer.io |5354 Define bounded contexts: each service owns its data and exposes it only via APIs. Never share databases between services.55562. **Implement an API composition layer (BFF)**5758 A Backend-for-Frontend (BFF) aggregates multiple upstream APIs into a single request, tailored to what the frontend needs:5960 ```typescript61 // bff/src/routes/product-page.ts62 import {getProduct} from '../services/catalog';63 import {getSearchReviews} from '../services/reviews';64 import {getRecommendations} from '../services/recommendations';65 import {getInventory} from '../services/inventory';6667 export async function productPageData(productId: string, customerId?: string) {68 // Parallel fetch from independent services69 const [product, inventory, recommendations] = await Promise.all([70 getProduct(productId),71 getInventory(productId),72 getRecommendations(productId, customerId),73 ]);7475 // Sequential: reviews needs product.sku76 const reviews = await getSearchReviews(product.sku);7778 return {79 product,80 inventory,81 recommendations,82 reviews,83 };84 }85 ```8687 Expose the BFF as a GraphQL API using schema stitching or federation:8889 ```typescript90 import {buildHTTPExecutor} from '@graphql-tools/executor-http';91 import {stitchSchemas} from '@graphql-tools/stitch';9293 const gatewaySchema = await stitchSchemas({94 subschemas: [95 { schema: await introspectSchema(catalogExecutor), executor: catalogExecutor },96 { schema: await introspectSchema(inventoryExecutor), executor: inventoryExecutor },97 { schema: await introspectSchema(reviewsExecutor), executor: reviewsExecutor },98 ],99 });100 ```1011023. **Use event-driven architecture for cross-service coordination**103104 Services should communicate asynchronously for workflows that span multiple capabilities (order placed → inventory reserved → fulfillment triggered → email sent):105106 ```typescript107 // Order service publishes an event after checkout108 import {EventBridge} from '@aws-sdk/client-eventbridge';109110 const eventBridge = new EventBridge({region: 'us-east-1'});111112 async function publishOrderPlaced(order: Order) {113 await eventBridge.putEvents({114 Entries: [115 {116 Source: 'commerce.orders',117 DetailType: 'OrderPlaced',118 Detail: JSON.stringify({119 orderId: order.id,120 customerId: order.customerId,121 lineItems: order.lineItems,122 totalAmount: order.totalAmount,123 currency: order.currency,124 }),125 EventBusName: 'commerce-events',126 },127 ],128 });129 }130131 // Inventory service subscribes and reserves stock132 // EventBridge rule routes OrderPlaced → Lambda → inventory-service133 export async function handler(event: EventBridgeEvent<'OrderPlaced', OrderPayload>) {134 const {orderId, lineItems} = event.detail;135 await reserveInventory(lineItems);136 await publishInventoryReserved(orderId);137 }138 ```1391404. **Implement the Saga pattern for distributed transactions**141142 When a multi-step workflow must be atomic across services, use orchestrated sagas with compensating transactions:143144 ```typescript145 // Choreography-based saga for order fulfillment146 // Each service publishes events and reacts to others147148 // Order Service149 on('CheckoutCompleted', async ({orderId, paymentIntentId}) => {150 await orders.create({orderId, status: 'pending_payment'});151 await publish('OrderCreated', {orderId, paymentIntentId});152 });153154 // Payment Service155 on('OrderCreated', async ({orderId, paymentIntentId}) => {156 try {157 await capturePayment(paymentIntentId);158 await publish('PaymentCaptured', {orderId});159 } catch (err) {160 await publish('PaymentFailed', {orderId, reason: err.message});161 }162 });163164 // Fulfillment Service165 on('PaymentCaptured', async ({orderId}) => {166 await fulfillment.schedule(orderId);167 });168169 // Order Service — compensate on failure170 on('PaymentFailed', async ({orderId}) => {171 await orders.update(orderId, {status: 'payment_failed'});172 await releaseInventory(orderId);173 await notifyCustomer(orderId, 'payment_failed');174 });175 ```1761775. **Manage API versioning and backward compatibility**178179 In a composable stack, services evolve independently. Use additive versioning strategies:180181 ```typescript182 // Use content negotiation or URL versioning183 // GET /api/v2/products/:id184 // Accept: application/vnd.commerce.product.v2+json185186 // Apply the Tolerant Reader pattern — ignore unknown fields187 interface ProductV1 {188 id: string;189 name: string;190 price: number;191 }192193 // V2 adds fields — existing consumers still work194 interface ProductV2 extends ProductV1 {195 categories?: string[];196 attributes?: Record<string, string>;197 brand?: string;198 }199200 // Use feature flags to roll out breaking changes201 async function getProduct(id: string, apiVersion: '1' | '2' = '1') {202 const product = await catalog.findById(id);203 return apiVersion === '2' ? toProductV2(product) : toProductV1(product);204 }205 ```2062076. **Implement circuit breakers for resilience**208209 When one service degrades, prevent cascading failures across the entire stack:210211 ```typescript212 import CircuitBreaker from 'opossum';213214 const inventoryCircuit = new CircuitBreaker(checkInventory, {215 timeout: 3000, // Request timeout in ms216 errorThresholdPercentage: 50, // Open circuit if 50% of requests fail217 resetTimeout: 30000, // Try again after 30 seconds218 });219220 inventoryCircuit.fallback(() => ({221 available: true, // Optimistic fallback — show as available222 quantity: null, // Don't show exact quantity223 }));224225 inventoryCircuit.on('open', () => {226 logger.warn('Inventory service circuit OPEN — using fallback');227 metrics.increment('circuit_breaker.inventory.open');228 });229230 // Usage231 const stock = await inventoryCircuit.fire(productId);232 ```233234## Examples235236### commercetools SDK integration for catalog237238```typescript239import {createApiBuilderFromCtpClient} from '@commercetools/platform-sdk';240import {ClientBuilder} from '@commercetools/sdk-client-v2';241242const ctpClient = new ClientBuilder()243 .withProjectKey(process.env.CTP_PROJECT_KEY!)244 .withClientCredentialsFlow({245 host: 'https://auth.us-central1.gcp.commercetools.com',246 projectKey: process.env.CTP_PROJECT_KEY!,247 credentials: {248 clientId: process.env.CTP_CLIENT_ID!,249 clientSecret: process.env.CTP_CLIENT_SECRET!,250 },251 scopes: ['manage_project:' + process.env.CTP_PROJECT_KEY],252 fetch,253 })254 .withHttpMiddleware({host: 'https://api.us-central1.gcp.commercetools.com', fetch})255 .build();256257const apiRoot = createApiBuilderFromCtpClient(ctpClient).withProjectKey({258 projectKey: process.env.CTP_PROJECT_KEY!,259});260261// Fetch product by slug262const product = await apiRoot263 .products()264 .get({queryArgs: {where: `slug(en="${slug}")`, expand: ['productType']}})265 .execute();266```267268### Algolia search with Contentful CMS enrichment269270```typescript271import algoliasearch from 'algoliasearch';272import {createClient as createContentfulClient} from 'contentful';273274const algolia = algoliasearch(process.env.ALGOLIA_APP_ID!, process.env.ALGOLIA_SEARCH_KEY!);275const contentful = createContentfulClient({space: process.env.CONTENTFUL_SPACE_ID!, accessToken: process.env.CONTENTFUL_TOKEN!});276277async function searchProducts(query: string, filters?: string) {278 // Search in Algolia for product IDs and structured data279 const {hits} = await algolia.initIndex('products').search<AlgoliaProduct>(query, {280 filters,281 attributesToRetrieve: ['objectID', 'name', 'price', 'contentfulEntryId'],282 });283284 // Enrich with rich content from Contentful285 const contentEntryIds = hits.map(h => h.contentfulEntryId).filter(Boolean);286 const contentEntries = await contentful.getEntries({287 content_type: 'productPage',288 'sys.id[in]': contentEntryIds.join(','),289 });290291 const contentMap = new Map(contentEntries.items.map(e => [e.sys.id, e]));292293 return hits.map(hit => ({294 ...hit,295 content: contentMap.get(hit.contentfulEntryId),296 }));297}298```299300## Best Practices301302- **Define a clear data ownership model** — each piece of data has exactly one system of record; other services read from it via API, never write to it directly303- **Design for eventual consistency** — cross-service data will be temporarily inconsistent after an event; build UIs and workflows that tolerate this (e.g., optimistic inventory, compensating transactions)304- **Use an API gateway for cross-cutting concerns** — authentication, rate limiting, request logging, and SSL termination belong at the gateway, not in every service305- **Implement distributed tracing** — use OpenTelemetry with a trace ID propagated across all service calls; this is essential for debugging multi-service request failures306- **Version your events** — event schemas change over time; include a `schemaVersion` field in every event payload and maintain backward-compatible consumers307- **Use a service mesh for service-to-service traffic** — tools like Istio or AWS App Mesh handle mutual TLS, load balancing, and retries at the infrastructure layer308- **Start with a modular monolith** — decompose into microservices only when you have clear team ownership boundaries and operational maturity; premature decomposition creates accidental complexity309310## Common Pitfalls311312| Problem | Solution |313|---------|----------|314| Distributed transaction failures leave data inconsistent | Implement sagas with compensating transactions; use outbox pattern to guarantee event publication after DB write |315| Service latency compounds in the critical path | Move non-critical services off the critical path using async events; set aggressive timeouts and circuit breakers on all external calls |316| API contract breaks downstream consumers | Use consumer-driven contract testing (Pact) so breaking changes are caught before deployment |317| Shared database creates hidden coupling | Enforce the rule: one service, one schema; use event sourcing or change data capture for cross-service data propagation |318| Debugging failures across 10 services | Implement distributed tracing with OpenTelemetry from day one; correlate logs with a single trace ID per user request |319320## Related Skills321322- @commerce-api-gateway323- @saleor-development324- @shopify-hydrogen325- @webhook-architecture326- @flash-sale-scaling327- @edge-commerce