Skip to content

Service-Oriented Architecture (SOA) ​

"Service Oriented Architecture (SOA) is a paradigm for organizing and utilizing distributed capabilities that may be under the control of different ownership domains." — OASIS, Reference Model for Service Oriented Architecture 1.0, OASIS Standard, 12 October 2006

Summary: SOA is the idea that a company's capabilities should be offered as network services with published contracts; the 2000s implementation (SOAP, WSDL, an ESB, a central orchestrator, a canonical data model) over-centralised the idea and failed in many places, but the contract-first core lives on inside microservices, API management and every integration with a legacy SOAP endpoint. Focus: history, the OASIS definition, the principles, the four-layer service taxonomy, the ESB and orchestration engine, WS-* and why it was heavy, canonical data model, governance and reuse myths, SOA versus microservices, service-based architecture, legacy integration, and one bank transfer built in SOA style and in microservice style, with Go and Laravel code. Learning goal: Given a system, say whether it is SOA, microservices or a distributed monolith; decide which SOA ideas to keep; consume a SOAP service safely behind an anti-corruption layer; and expose the same capability as a contract-first REST service.

This chapter sits in the architecture styles group: styles vs patterns explains what a style is; client-server and pipe-and-filter are its neighbours; microservices architecture is the successor and holds the full treatment. Here we cover the 2000s style in full, so that when somebody says "that is just SOA" you know exactly what is the same and what is not. Messaging details (canonical model, routing, saga) are owned by the messaging path; we give only the SOA angle and link out.

Page map ​

If you are looking forGo to
The whole chapter in a few tablesEverything in one minute
Why SOA appeared and why people stopped saying itWhy it exists
CORBA, DCOM, web services, ESB, microservicesWhere it comes from
The eight principles, one block eachPrinciples
Business / enterprise / application / infrastructure servicesService taxonomy
ESB, mediation, orchestration engine, BPELESB and orchestration
SOAP, WSDL, UDDI, WS-Security, WS-ReliableMessagingThe WS-* stack
Canonical data model and what it costsCanonical data model
Governance, reuse, "the SOA that failed"Governance and reuse myths
SOA vs microservices tableSOA vs microservices
Service-based architecture (the middle way)Service-based architecture
What survivedWhere SOA ideas survive
Calling a SOAP endpoint from Go and LaravelLegacy integration, Go, Laravel
Orchestrated vs choreographed bank transferWorked example
Monolith to distributed systemIn architecture
Hands-on exerciseLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked below.

TermIn plain wordsTiny exampleWhat goes wrong without it
ServiceA capability reachable through a published interfaceTransferFunds over SOAPConsumers reach into internals
Service contractThe machine-readable promise of the interfaceA WSDL file or an OpenAPI fileEveryone guesses the message format
SOAPXML envelope protocol for messagesEnvelope / Header / BodyEvery integration invents its own wire format
WSDLXML description of operations, messages, binding, addresslegacy-transfer.wsdlNo generated clients, no checking
UDDIA registry to publish and find servicesPublic "yellow pages" of servicesNobody knows what exists (and it was still not adopted)
WS-*Add-on specs: security, reliability, policy, addressingWS-Security signature in a headerEach vendor extends SOAP differently
ESBA central bus doing mediation, routing, transformationMule, IBM Integration Bus, Oracle Service BusPoint-to-point spaghetti (and, if misused, a new single brain)
OrchestrationOne central process calls services in orderA BPEL process for "open account"Business flow is scattered across callers
ChoreographyServices react to each other's events, no centreTransferApproved triggers debitThe centre becomes the bottleneck
Canonical data modelOne shared enterprise message vocabularyA global Customer schemaN-by-N translators between systems
Service-based architectureA few coarse services, often one shared database4-12 domain services plus one UIMicroservices cost without the need

SOA in one picture of trade-offs.

You gainYou pay
Reuse of capabilities across applicationsA central team and a queue in front of every change
Interoperability between Java, .NET, mainframeHeavy XML, heavy tooling, heavy specs
One place for security, logging, routingA single point of failure and of blame
Legacy systems become callableWrappers that freeze legacy behaviour

The four service types (Richards & Ford, orchestration-driven SOA):

TypeGranularityOwnerExample
Business serviceCoarse, entry pointBusiness analysts + architectsTransferFunds
Enterprise serviceFine, shared, reusableShared-services teamGetBalance, CreateCustomer
Application serviceOne application onlyThat application's teamMainframeWrapper.Post
Infrastructure serviceCross-cuttingPlatform teamAudit, auth, logging

Why it exists ​

By the late 1990s a large company ran dozens of applications: a mainframe for accounts, packaged ERP, CRM, a web front end, partner links. Integrating them was done point to point, each pair with its own file format or remote-object binding. N applications needed up to N×(N−1) connections. The SOA idea answers three problems at once: reach (make every capability callable from anywhere), neutrality (no dependency on one language or vendor) and reuse (write "calculate quote" once, call it from everywhere).

Point-to-point integrationService-oriented integration
Each pair agrees a private formatEach service publishes one contract
Adding application N+1 means N new linksAdding it means one new contract (in theory)
Knowledge of internals leaksConsumers see only the interface
Cheap for 3 systems, chaos for 30Overhead for 3 systems, tolerable for 30

The analogy we reuse: a company reception desk. Visitors never walk into departments; they ask the front desk, which knows the right department, translates the request into the department's forms and phones back the answer. A good reception desk (a thin gateway) is a gift. A reception desk that also decides pricing, approves refunds and rewrites contracts (an ESB with business rules) becomes the most powerful and most overloaded person in the company.

Three common misunderstandings, up front ​

  1. "SOA means SOAP and web services." No. OASIS defines SOA as a paradigm and explicitly says the reference model is independent of technology. SOAP was the common implementation of the 2000s, not the definition. REST/JSON services, message queues and gRPC can all be service-oriented.
  2. "SOA is dead, microservices replaced it." Microservices inherit the core (services with contracts, loose coupling) and reject the 2000s implementation habits (central bus, canonical model, central governance). Fowler writes that some consider microservices "perhaps service orientation done right".
  3. "Reuse is the point of services." Reuse was the sales pitch and the main disappointment. The durable benefit is independent change behind a stable contract, not that ten teams share one Customer service.

Where it comes from ​

1990sCORBA, DCOM2000-2003SOAP, WSDL, UDDI2003-2012SOA + ESB + WS-*2010sREST, cloud, Docker2014 onwardMicroservicesremote objects,tight couplingXML contracts,platform neutralcentral governance,canonical modelscheap HTTP APIs,JSONown data, own deploy,dumb pipesLegacy SOAP endpoints in banks and government stay alive in every column

The timeline above is the story in five boxes. The details, with the reading status of each claim:

PeriodWhat happenedHow we know
Early 1990sCORBA (OMG) and DCOM (Microsoft) offer remote objects: call a method on an object in another process or machineSecondary knowledge (Fowler's "CORBA with angle brackets" jab confirms the lineage); original specs not read
8 May 2000SOAP 1.1 published as a W3C NoteRead: the SOAP 1.2 spec cites http://www.w3.org/TR/2000/NOTE-SOAP-20000508/
August 2000UDDI written, with a vision of public service brokersWikipedia (secondary)
15 March 2001WSDL 1.1 published as a W3C NoteRead: the Note's front page
27 April 2007SOAP 1.2 Part 1 Second Edition is a W3C Recommendation; it "supercedes all previous versions of SOAP, including SOAP Version 1.1"Read
26 June 2007WSDL 2.0 is a W3C RecommendationRead
2005Fowler: "SOA means so many different things to different people"Read
January 2006IBM, Microsoft and SAP close their public UDDI nodesWikipedia (secondary)
12 October 2006OASIS publishes the SOA Reference Model 1.0Read
25 March 2014Fowler and Lewis publish the microservices article, with a Microservices and SOA sectionRead

CORBA and DCOM: the objects-over-the-wire era ​

Good to know In plain words: the first idea was to make a remote object feel like a local object: call account.debit(100) and let the middleware ship it over the network.

Common misunderstanding: "distributed objects were just early microservices." They hid the network, so callers made chatty fine-grained calls, shared object models and broke on every change. Services were designed to expose the network cost: coarse messages, explicit contracts, no shared object graph.

Web services and the SOA wave ​

SOAP gave a platform-neutral envelope over HTTP, WSDL described it, UDDI was supposed to publish it. Fowler's 2005 note records the confusion that followed: for some people SOA meant WS-* standards, for others "any form of XML over http", for others asynchronous messaging "EAI without all the expensive EAI vendors", and in its worst form "CORBA with angle brackets". OASIS answered with a reference model deliberately above technology.

The ESB and the failure ​

Vendors sold the Enterprise Service Bus as the product that is SOA. Companies bought it, put every integration in it, and often wrapped monoliths in services without changing them. Fowler lists the result: "the tendency to hide complexity away in ESB's, to failed multi-year initiatives that cost millions and deliver no value, to centralised governance models that actively inhibit change".

Microservices and the settling ​

Teams at web companies (Fowler cites Netflix, who called their style "fine-grained SOA") kept the services and dropped the bus, the canonical model and the committee. Today the honest summary is: service orientation won; the orchestration-driven ESB style did not.

The OASIS definition, precisely ​

Must-know The OASIS reference model defines a service as "a mechanism to enable access to one or more capabilities, where the access is provided using a prescribed interface and is exercised consistent with constraints and policies as specified by the service description." Three words carry the weight: capability (what it does for someone), prescribed interface (the contract) and service description (machine-readable policy).
OASIS conceptMeaningWhere it shows up in practice
VisibilityProvider and consumer can see each other (awareness, willingness, reachability)Registry, API portal, DNS name
InteractionUsing a capability through messages, with a real-world effectAn HTTP call that moves money
Real-world effectObservable result of an interactionBalance changes
Service descriptionInformation needed to use the serviceWSDL, OpenAPI
Contract and policyWhat both sides agree to, plus conditionsRate limit, authentication, SLA
Execution contextWhat is needed for interaction to happenSecurity domain, transport, transaction context

The reference model also states what it leaves out: "in this Reference Model we do not address the orchestration of multiple services, although orchestration and choreography may be part of the process model." Remember this: orchestration and the ESB are not in the definition of SOA. They are one popular way to build it.

Principles ​

Thomas Erl's service-orientation principles are the best-known list. His own site could not be fetched by us (the pages need a browser), so the eight names below are written from memory of his books, not from a page we read; Wikipedia's SOA article lists a slightly different set (it adds service longevity, location transparency, granularity and normalization). The one-line meanings are our paraphrase.

Standardized service contract Must-know ​

In plain words: every service describes itself in an agreed, machine-readable way, and the contract is designed before the code. Common misunderstanding: "the contract is generated from the code, so it is automatically standard." A contract generated from your classes leaks your internals; contract-first means the WSDL or OpenAPI file is written by hand first and both sides code against it. Real scenario: the bank's transfer service publishes legacy-transfer.wsdl; any client generates stubs from it.

Loose coupling Must-know ​

In plain words: consumers depend on the contract, not on the provider's language, database or location. Common misunderstanding: "SOAP over HTTP is loosely coupled." A synchronous call with a shared canonical schema is tightly coupled in time and in data; protocol choice does not decide coupling.

Abstraction Important ​

In plain words: the contract hides the how. Callers know "TransferFunds", not which tables change. Common misunderstanding: "wrapping a monolith in a service is abstraction." It is only a facade; the monolith's release cycle still gates every change.

Reusability Important ​

In plain words: design services so more than one consumer can use them. Common misunderstanding: "make everything reusable from day one." Generic services serve nobody well; reuse is discovered after the second real consumer, not designed for imagined ones (see governance and reuse myths).

Autonomy Important ​

In plain words: a service controls its own logic and runtime, so it can change and fail without taking others along. Common misunderstanding: "autonomy is only about deployment." Without data autonomy (its own store) two services sharing one schema are one service in two processes; see data ownership.

Statelessness Important ​

In plain words: a service does not keep per-caller conversation state between requests; state travels in the message or lives in a store. Common misunderstanding: "stateless means no database." It means no session memory in the process, which is what lets you run N identical copies.

Discoverability Good to know ​

In plain words: services carry metadata so people (and tools) can find and understand them. Common misunderstanding: "we need a UDDI registry." UDDI was not widely adopted; a developer portal and an API catalogue do the job today, and see service discovery for runtime lookup.

Composability Important ​

In plain words: services can be combined into bigger services, whatever the size of the combination. Common misunderstanding: "composition requires a central engine." Composition by orchestration needs one; by choreography it needs none (next section).

PrincipleTest questionFailing exampleModern equivalent
Standardized contractCan I generate a client without talking to the team?Contract is a Word documentOpenAPI, protobuf, WSDL
Loose couplingCan the provider change language or database without me noticing?Shared database tableVersioned API
AbstractionDo I know only the capability, not the internals?Error text exposes SQLRFC 9457 problem types
ReusabilityDoes a second consumer use it unchanged?One-off field added per consumerStable public API
AutonomyCan it deploy and fail alone?Needs the ESB to startIndependent deploy
StatelessnessCan any instance answer?Sticky sessionToken plus store
DiscoverabilityCan a newcomer find it in 5 minutes?Wiki page from 2011API catalogue
ComposabilityCan it be one step of a bigger flow?Operation returns a UI fragmentIdempotent operations

Service taxonomy: business, enterprise, application, infrastructure ​

Consumers: web portal, mobile app, partner B2B, batch jobsBusiness services (coarse, entry points)ExecuteTrade, TransferFunds, OpenAccount: one verb a business person recognisesOrchestration engine + ESB: the central brain and the smart pipemediation, routing, protocol and format transformation, BPEL-style process flowsEnterprise services (fine, shared, reusable)CreateCustomer, CalculateQuote, GetBalanceowned by a shared-services team, canonical data modelInfrastructure servicesauth, audit, logging,monitoring, notificationApplication services (one application only)mainframe wrapper, CRM adapter, ERP adapterApplications and databases (often shared, often a monolith behind each wrapper)

Richards and Ford (Fundamentals of Software Architecture, orchestration-driven service-oriented architecture chapter; the book is not freely fetchable, so this section is our paraphrase, not a quotation) describe the style as a stack of four service types joined by an orchestration engine:

LayerRoleOwned byExample (bank)Typical problem
Business servicesEntry points; just a name and an input/output, little or no codeBusiness + architectsTransferFunds, OpenAccountThey are empty shells; real logic lives in the orchestrator
Enterprise servicesFine-grained, shared, "atomic" building blocksShared-services teamGetBalance, ValidateIban, CreateCustomerEveryone depends on them, so nobody can change them
Application servicesSpecific to one application, not sharedOne application teamPostLedgerEntry for the core banking systemDuplicates enterprise services
Infrastructure servicesCross-cutting plumbingPlatform teamAuthentication, audit, monitoringOften the only layer that really succeeds

Common misunderstanding: "this is a good layered design." Look at one change: adding a field to TransferFunds means touching the business service, the orchestration flow, a canonical schema, possibly an enterprise service and each wrapper. Richards and Ford rate this style poorly for agility and deployment because technical layers cut across every business change. Compare with layered monolith: same problem, now across a network.

A request through the layers ​

 1  Portal            -> Business service TransferFunds (SOAP, WS-Security header)
 2  ESB               -> authenticate via infrastructure service (audit logged)
 3  Orchestrator      -> enterprise service ValidateIban(from), ValidateIban(to)
 4  Orchestrator      -> enterprise service GetBalance(from)
 5  Orchestrator      -> application service PostLedgerEntry (mainframe wrapper)
 6  Orchestrator      -> enterprise service NotifyCustomer
 7  ESB               -> transforms canonical Transfer to mainframe fixed-width record
 8  Business service  <- response mapped back to canonical, then to the portal

Eight hops, one transaction in the customer's head, no database transaction anywhere. Sections worked example and saga deal with what happens when step 5 succeeds and step 6 fails.

The ESB and the orchestration engine ​

Must-know In plain words: an Enterprise Service Bus is a central switchboard: every call goes through it, and it can reroute, convert and sequence calls.

Common misunderstanding: "an ESB is a message broker." A broker (RabbitMQ, Kafka) moves messages and stays dumb; an ESB adds mediation, protocol bridging, transformation, orchestration and rules. The difference is the whole smart pipes versus dumb pipes debate. The Enterprise Integration Patterns catalogue has a smaller Message Broker pattern that only decouples sender from receiver.

ESB capabilityWhat it doesExampleRisk
MediationSits between consumer and provider, hides the endpointConsumer calls a virtual addressThe bus becomes a mandatory hop
RoutingChooses the destination by content, rules, versionDomestic vs international transfer routeRouting rules become business logic
TransformationConverts formats (XML, fixed-width, JSON) via XSLT or mappingCanonical Transfer to mainframe recordMappings nobody can test
Protocol bridgingHTTP to JMS to FTP to MQSOAP in, MQ outHidden retries and timeouts
OrchestrationRuns a process definition (BPEL, BPMN) over servicesOpen account: KYC, create, notifyThe centre owns all business flow
Security policyApplies WS-Security, token mapping, throttlingVerify signature onceSingle point of attack
Monitoring and auditOne place to log every callCentral audit trailLog volume, privacy

Products people met. Mule ESB (MuleSoft), IBM WebSphere ESB and IBM Integration Bus, Oracle Service Bus, TIBCO BusinessWorks, WSO2 ESB, Apache ServiceMix, Apache Camel as a library, Microsoft BizTalk Server. Today the same job is done by API gateways, iPaaS products and Camel/Spring Integration code.

Orchestration language. BPEL (Business Process Execution Language for web services, an OASIS standard) described a process as XML calling services in order, with fault and compensation handlers. Fowler's microservices article contrasts it with the microservices approach: services "are choreographed using simple RESTish protocols rather than complex protocols such as WS-Choreography or BPEL or orchestration by a central tool."

Orchestration vs choreography ​

Orchestration (SOA)Orchestratorowns flow + stateFraudAccountsNotify1 call, wait, 2 call, wait, 3 callcompensation lives in one placerisk: the brain becomes the bottleneckChoreography (microservices)PaymentsFraudAccountsEvent bus: dumb pipe (RabbitMQ, Kafka)NotifyLedgerno owner: flow emerges from who listensrisk: nobody can see the whole process

Analogy: a conductor tells each musician when to play (orchestration); dancers at a ballroom each know the music and react to their neighbours (choreography).

PropertyOrchestrationChoreography
Who knows the whole flowThe orchestratorNobody; it emerges
CouplingServices know nothing of each other; orchestrator knows allServices know the events they react to
Failure handlingCompensation in one placeEach service compensates its own part
VisibilityRead one process definitionNeeds tracing and event catalogue
ChangeEdit one flow; the centre is a team bottleneckEdit one service; risk of surprising consumers
Typical styleSOA with BPEL or an ESBMicroservices with events
DetailSaga patternEvent-driven architecture

Neither is "the right one". The worked example below uses both on the same business operation.

The WS-* stack and why it was heavy ​

Important In plain words: web services started as "send XML over HTTP"; every enterprise need (security, reliability, transactions, addressing) was then added as another XML specification stacked on SOAP headers.

Common misunderstanding: "SOAP is just XML over HTTP." SOAP is a messaging framework: an envelope with a header (extension points) and a body, a processing model with intermediaries, and a fault model; HTTP is only one binding. SOAP 1.2 describes itself as "a lightweight protocol intended for exchanging structured information in a decentralized, distributed environment" and the real weight comes from what is stacked on top.

SpecificationPurposeStandards body and version we readWhy it adds weight
SOAPEnvelope, header, body, fault, processing modelW3C SOAP 1.2 Part 1, Second Edition, 27 April 2007Verbose XML, namespaces on every element
WSDLDescribe operations, messages, bindings, addressesW3C WSDL 1.1 Note (2001); WSDL 2.0 Recommendation (2007)Large documents, code generators differ
XML Schema (XSD)Message typesW3CComplex type system, versioning pain
UDDIPublish and find servicesOASIS (committee finished 2007, per Wikipedia)Registry nobody kept up to date
WS-SecuritySigning and encrypting parts of a message, tokensOASIS Standard 1.1.1, 18 May 2012XML signature canonicalisation, big headers
WS-ReliableMessagingReliable delivery between endpoints across failuresOASIS Standard 1.2, 2 February 2009Sequences, acknowledgements, state on both ends
WS-Addressing, WS-Policy, WS-Transaction, WS-CoordinationRouting headers, policy, distributed transactionsW3C / OASIS (not read by us)Each adds headers and a coordinator
BPEL, WS-CDLOrchestration and choreography languagesOASIS, W3C (not read by us)Programming in XML

WS-Security's abstract says it "describes enhancements to SOAP messaging to provide message integrity and confidentiality"; WS-ReliableMessaging "describes a protocol that allows messages to be transferred reliably between nodes implementing this protocol in the presence of software component, system, or network failures." Both solve real problems. The cost: a sender needs a library that implements the whole stack in a compatible way, and interoperability between vendors needed extra "profiles" (WS-I Basic Profile).

Why it was heavy, in one list. XML verbosity and namespace handling; code generation from WSDL with tool-specific quirks; many specifications each with versions and vendor extensions; transport security duplicated (TLS vs WS-Security); debugging by reading envelopes; and a framework per language (Apache Axis, Apache CXF, Microsoft WCF). Fowler's complaint: "central standards that have reached a complexity that is, frankly, breathtaking."

A SOAP 1.1 exchange as it appears on the wire:

 1  POST /ws/transfer HTTP/1.1
 2  Content-Type: text/xml; charset=utf-8
 3  SOAPAction: "urn:example:bank:transfer:v1/TransferFunds"
 4  <Envelope> <Body> <TransferFunds> from, to, amount, currency, reference
 5  HTTP/1.1 500 Internal Server Error          <- SOAP 1.1 faults use HTTP 500
 6  <Envelope> <Body> <Fault> faultcode, faultstring, detail/ErrorCode=51

Remember line 5: a SOAP fault travels as HTTP 500 with a body. Our Go client decodes the body before looking at the status for exactly this reason.

Canonical data model ​

Important In plain words: instead of translating every system's format to every other's, agree one enterprise-wide format and translate each system to and from it.

Common misunderstanding: "a canonical model gives us one clean enterprise data model." It gives you a negotiation that lasts years. The Enterprise Integration Patterns page makes the arithmetic case: with 2 applications you need 2 translators directly and 4 with a canonical model; with 6 applications 30 without and 12 with. That is the benefit. The cost is that every consumer and provider is now coupled to the committee's Customer schema.

 1  Without canonical model: A→B, A→C, B→A, B→C, C→A, C→B = 6 translators (3 apps)
 2  With canonical model:    A→M, M→A, B→M, M→B, C→M, M→C = 6 translators (3 apps)
 3  Break-even at 3 applications; 6 apps: 30 vs 12
 4  New field in M: every translator and every consumer is reviewed
AspectCanonical modelPer-pair translationBounded contexts (DDD)
Translators needed2NN×(N−1)One per relationship, in an ACL
Change to a fieldCommittee, all usersTwo partiesThe owning context only
Meaning of "Customer"One, compromisedWhatever each pair agreesOne per context
Failure modeLowest common denominator, years of meetingsSpaghettiDuplicated concept, explicit translation
Where it fitsStable domains (payments messages, healthcare HL7, ISO 20022)A handful of systemsMost product companies

Our own rule: use a canonical message format only where an industry has already standardised one (ISO 20022 for payments, HL7 for health); do not invent an enterprise-wide domain model. See message transformation for the mechanics and context maps for the DDD alternative.

Governance and reuse myths ​

Important In plain words: SOA programmes created a governance board to approve services, reviews to prevent duplicates and a catalogue to find reusable ones, hoping every new project would assemble existing services.

Common misunderstanding: "if we build reusable services first, projects will be cheaper." Reuse requires a stable, generic service; generic services cost more to build, nobody pays for the extra, and every consumer then blocks on the shared team. Fowler's wording for the outcome: "centralised governance models that actively inhibit change".

MythWhat actually happenedWhat to do instead
"Build reusable services, assemble apps later"Services built for nobody; consumers needed different fieldsBuild for the first consumer, generalise at the third
"A central board keeps the architecture clean"Weeks per approval, workarounds in secretGuardrails (linters, templates), review by exception
"A registry makes services discoverable"UDDI not adopted; the registry rottedDeveloper portal owned by the provider team
"The ESB gives loose coupling"Every flow depended on the bus teamSmart endpoints, dumb pipes
"Wrap the monolith and you have SOA"Same release train, new latencyExtract along business capabilities
"One canonical model reduces cost"The model became the most-changed assetPer-context models plus explicit translation
"Orchestration engine = business agility"Business logic hidden in XML flowsKeep logic in code with tests

Thoughtworks' Technology Radar put the same warning on the hold ring under Overambitious API gateways: "One of our common complaints is the pushing of business smarts into middleware, resulting in application servers and enterprise service buses with ambitions to run critical application logic." The advice: keep generic concerns (authentication, rate limiting) in the gateway and "any domain smarts such as data transformation or rule processing" in the owning services.

SOA vs microservices ​

SOA: smart pipes, dumb endpointsESB / orchestration enginerouting, transformation, rules,process flow, security policyBillingCRMERPMainframeendpoints are thin wrappers; logic leaks into the buschange anything = touch the bus teamMicroservices: smart endpoints, dumb pipesOrdersPaymentsShippingHTTP / broker: moves bytes onlyOrders DBPayments DBShipping DBeach service owns logic and datachange one = deploy oneMust-know In plain words: SOA put the smartness in the pipe (the bus) and made the endpoints thin; microservices put it in the endpoints and made the pipe dumb.

Common misunderstanding: "microservices are small SOA services." Size is the least interesting difference. Fowler: "the microservice style is very similar to what some advocates of SOA have been in favor of. The problem, however, is that SOA means too many different things, and that most of the time that we come across something called 'SOA' it's significantly different to the style we're describing here, usually due to a focus on ESBs used to integrate monolithic applications."

DimensionSOA (orchestration-driven, 2000s)MicroservicesService-based architecture
Primary goalEnterprise-wide reuse and integrationIndependent change and deployPragmatic domain split
Service sizeBusiness services very coarse, enterprise services very fineFine, one bounded contextCoarse (about 4 to 12 domain services)
DataShared databases behind wrappers, canonical modelDatabase per serviceOften one shared database
PipeSmart: ESB with routing, transformation, rulesDumb: HTTP or brokerDirect calls from UI; little middleware
Flow controlCentral orchestrator (BPEL, BPMN)Choreography with events, local sagasWithin a service, local transactions
GovernanceCentral board, enterprise standardsDecentralised, team standardsLight, architect-led
DeploymentServices in application servers, often released togetherIndependent pipelines and containersA few independent deployments
ProtocolsSOAP, WSDL, WS-*, JMS, MQREST/JSON, gRPC, Kafka, AMQPREST or RPC from the UI
Contract styleCanonical XML schemasPer-service API, consumer-driven contractsShared or per-service
Failure handlingReliable messaging, XA / compensation in the engineTimeouts, retries, circuit breakers, sagasDatabase transactions
Typical teamCentral integration team plus app teamsProduct team owns a service end to endDomain teams, shared platform
Where it hurtsBus bottleneck, committees, XML mappingOperations, distributed data, observabilityShared schema coupling

Short rule: if one team must be consulted for every integration change, you have SOA in the 2000s sense, whatever the services are called. See the full microservices treatment in microservices architecture, service communication and API gateway, BFF and service mesh.

Service-based architecture: the pragmatic middle ​

Important In plain words: split the system into a handful of big, domain-shaped services (for example Orders, Payments, Customers), deployed separately, usually sharing one database, with the UI calling them directly.

Common misunderstanding: "service-based and service-oriented are the same thing." Wikipedia's SOA article has a note saying they "must not be confused", and Richards and Ford treat them as separate styles: service-based has no ESB, no enterprise-service layer, no canonical model.

PropertyService-based architecture (Richards & Ford, paraphrase)
Number of servicesTypically 4 to 12 coarse "domain services"
DatabaseUsually one shared database (can be split per domain with care)
IntegrationUI or API layer calls services directly; no orchestration engine
DeploymentEach domain service deployed independently; far fewer pipelines than microservices
StrengthsCheap, understandable, testable, good agility and fault isolation for the cost
WeaknessesCoarse services still share a schema; scalability and elasticity limited compared with microservices
Good fitMedium systems, teams of 10 to 50, parts of a modular monolith that need independent deployment

The middle way fits the sequence in monolith vs microservices vs modular monolith: a modular monolith first, a few extracted domain services next, microservices only where an independent scaling or team boundary demands it.

Where SOA ideas survive ​

SOA ideaWhere it lives nowExample
Contract-first designOpenAPI, protobuf, AsyncAPI, consumer-driven contract testscontract/transfers.openapi.yaml in this chapter
Service registryService discovery, developer portals, API cataloguesConsul, Kubernetes Services, Backstage
ESB mediation and policyAPI gateway and management: auth, quotas, versioning, analyticsKong, Apigee, AWS API Gateway, Traefik; see gateways
ESB protocol bridgingiPaaS and integration frameworksApache Camel, Spring Integration, MuleSoft
Canonical modelIndustry standards; schema registry for eventsISO 20022, Avro schemas in Confluent Schema Registry
Orchestration engineDurable workflow engines, sagasTemporal, Camunda, Laravel queue chains, see durable workflows
Enterprise integration patternsThe vocabulary of every broker-based systemRouter, Translator, Splitter; see routing
Infrastructure servicesPlatform capabilitiesCentral IdP, audit pipeline, observability
Service description and policyGateway policies, service mesh configurationmTLS, retries in Envoy

The EIP catalogue by Hohpe and Woolf is the longest-lived output of the SOA era; its patterns are the vocabulary of messaging today.

Legacy integration: SOAP endpoints still exist ​

Must-know In plain words: banks, insurers, tax and customs systems, telecom billing and ERP suites (SAP, Oracle) still publish SOAP/WSDL services, and they will for decades. You will consume them.

Common misunderstanding: "we will just call it from our domain code." Then the legacy decimal strings, response codes ("51"), namespaces and fault shapes spread into every service. Put the legacy contract behind an anti-corruption layer (a term from domain-driven design): an adapter that owns all translation, so the rest of the system sees a clean port. Microsoft's pattern page states its purpose: it "helps ensure that new component design remains uninfluenced by legacy implementations that might have different data models or business rules when you integrate with these legacy systems."

ConcernRule for SOAP integrationWhere in our code
BoundaryOne adapter implements the domain portacl/adapter.go, LegacyTransferAdapter.php
MoneyInteger minor units inside; decimal string only at the edgedecimal() in both adapters
ErrorsMap legacy codes to domain errors oncetranslate()
FaultsSOAP 1.1 faults arrive as HTTP 500 with a body: parse firstsoapclient/client.go
TimeoutsAlways set connect and total timeoutsconnection_timeout, Http::timeout()
RetriesOnly when the provider de-duplicates on a referenceReference field = idempotency key
WSDLCache it; do not fetch per requestWSDL_CACHE_DISK
Contract driftKeep a recorded fixture and a contract testclient_test.go round-trip
StranglerRoute new traffic to a new service, shrink the adapterstrangler fig

Go ​

Go's standard library has no WSDL code generator. For one or two operations it is simpler to model the envelope with encoding/xml structs than to generate stubs; for large WSDLs, generate structs with a tool and keep the same shape. The package doc of encoding/xml says it "implements a simple XML 1.0 parser that understands XML name spaces", and namespace tags (xml:"urn:... TransferFunds") are what make an envelope round-trip.

The domain port ​

go
// Package transfer is the domain model of the transfer capability.
// It knows nothing about SOAP, XML, HTTP or JSON.
package transfer

import (
	"context"
	"errors"
)

// Money is an integer amount of minor units (cents, rials) plus an ISO 4217 code.
type Money struct {
	Minor    int64
	Currency string
}

// Transfer is one request to move money between two accounts.
// ID doubles as the idempotency key towards every downstream system.
type Transfer struct {
	ID     string
	From   string
	To     string
	Amount Money
}

// Receipt proves the transfer was accepted by the system of record.
type Receipt struct {
	TransferID string
	AuthCode   string
}

// Domain errors. Callers branch on these, never on legacy response codes.
var (
	ErrInsufficientFunds = errors.New("insufficient funds")
	ErrAccountRestricted = errors.New("account restricted")
	ErrUnavailable       = errors.New("system of record unavailable") // retryable
	ErrRejected          = errors.New("transfer rejected")
)

// Port is what the rest of the system depends on. The SOAP adapter and a
// future native service both implement it.
type Port interface {
	Transfer(ctx context.Context, t Transfer) (Receipt, error)
}

A SOAP 1.1 client with encoding/xml ​

go
// Package soapclient is a minimal SOAP 1.1 client built on encoding/xml.
// Go has no WSDL code generator in the standard library, so the envelope,
// the operation messages and the Fault are plain structs.
package soapclient

import (
	"bytes"
	"context"
	"encoding/xml"
	"fmt"
	"io"
	"net/http"
)

const (
	// EnvelopeNS is the SOAP 1.1 envelope namespace.
	EnvelopeNS = "http://schemas.xmlsoap.org/soap/envelope/"
	// ServiceNS is the target namespace declared in the WSDL.
	ServiceNS = "urn:example:bank:transfer:v1"
	// ActionTransferFunds is the SOAPAction HTTP header value for the operation.
	ActionTransferFunds = ServiceNS + "/TransferFunds"
)

// TransferFundsRequest is the wrapped document/literal request message.
type TransferFundsRequest struct {
	XMLName     xml.Name `xml:"urn:example:bank:transfer:v1 TransferFunds"`
	FromAccount string   `xml:"fromAccount"`
	ToAccount   string   `xml:"toAccount"`
	Amount      string   `xml:"amount"` // decimal string such as "125.50"
	Currency    string   `xml:"currency"`
	Reference   string   `xml:"reference"`
}

// TransferFundsResponse is the success message.
type TransferFundsResponse struct {
	XMLName  xml.Name `xml:"urn:example:bank:transfer:v1 TransferFundsResponse"`
	Status   string   `xml:"status"`
	AuthCode string   `xml:"authCode"`
}

// Fault is the SOAP 1.1 fault. faultcode and faultstring are unqualified.
type Fault struct {
	Code   string `xml:"faultcode"`
	String string `xml:"faultstring"`
	Detail struct {
		ErrorCode string `xml:"ErrorCode"` // legacy business code, for example "51"
	} `xml:"detail"`
}

// FaultError lets callers use errors.As on a SOAP fault.
type FaultError struct{ Fault Fault }

func (e *FaultError) Error() string {
	return fmt.Sprintf("soap fault %s: %s (legacy code %q)", e.Fault.Code, e.Fault.String, e.Fault.Detail.ErrorCode)
}

type requestEnvelope struct {
	XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
	Body    struct {
		Content any `xml:",any"`
	} `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`
}

type responseEnvelope struct {
	XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
	Body    struct {
		Fault    *Fault                 `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault"`
		Response *TransferFundsResponse `xml:"urn:example:bank:transfer:v1 TransferFundsResponse"`
	} `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`
}

// Client calls one SOAP endpoint over HTTP POST.
type Client struct {
	Endpoint string
	HTTP     *http.Client
}

// TransferFunds sends the operation and decodes either the response or the fault.
func (c *Client) TransferFunds(ctx context.Context, in TransferFundsRequest) (*TransferFundsResponse, error) {
	var env requestEnvelope
	env.Body.Content = in
	payload, err := xml.Marshal(env)
	if err != nil {
		return nil, fmt.Errorf("marshal envelope: %w", err)
	}
	body := append([]byte(xml.Header), payload...)

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.Endpoint, bytes.NewReader(body))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "text/xml; charset=utf-8") // SOAP 1.1
	req.Header.Set("SOAPAction", `"`+ActionTransferFunds+`"`)

	hc := c.HTTP
	if hc == nil {
		hc = http.DefaultClient
	}
	res, err := hc.Do(req)
	if err != nil {
		return nil, fmt.Errorf("soap transport: %w", err)
	}
	defer res.Body.Close()
	raw, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
	if err != nil {
		return nil, fmt.Errorf("read soap response: %w", err)
	}

	// SOAP 1.1 over HTTP: faults come back as HTTP 500 with a Fault in the body,
	// so decode the body before looking at the status code.
	var out responseEnvelope
	if err := xml.Unmarshal(raw, &out); err != nil {
		return nil, fmt.Errorf("soap http %d, body is not a SOAP envelope: %w", res.StatusCode, err)
	}
	if out.Body.Fault != nil {
		return nil, &FaultError{Fault: *out.Body.Fault}
	}
	if out.Body.Response == nil {
		return nil, fmt.Errorf("soap http %d: empty body", res.StatusCode)
	}
	return out.Body.Response, nil
}

Three details to notice. The request body is any so one envelope type serves every operation. The response envelope has both Fault and Response pointers: whichever is non-nil tells you which one arrived. And the status code is read last because SOAP 1.1 faults come with HTTP 500. The httptest file next to it (client_test.go) runs a real round-trip for success and for a fault; go vet cannot catch namespace mistakes, a round-trip can.

The anti-corruption layer ​

go
// Package acl is the anti-corruption layer between the clean transfer domain
// and the legacy SOAP core-banking service. Everything legacy stays in here.
package acl

import (
	"context"
	"errors"
	"fmt"

	"academy/service-oriented-architecture/soapclient"
	"academy/service-oriented-architecture/transfer"
)

// Legacy is the part of the SOAP client the adapter needs (easy to fake).
type Legacy interface {
	TransferFunds(ctx context.Context, in soapclient.TransferFundsRequest) (*soapclient.TransferFundsResponse, error)
}

// Adapter implements transfer.Port on top of the legacy SOAP service.
type Adapter struct{ Legacy Legacy }

var _ transfer.Port = (*Adapter)(nil)

// exponents lists the minor-unit exponent per currency (ISO 4217).
var exponents = map[string]int{"EUR": 2, "USD": 2, "JPY": 0, "KWD": 3}

// Transfer translates the domain request, calls SOAP, translates the answer.
func (a *Adapter) Transfer(ctx context.Context, t transfer.Transfer) (transfer.Receipt, error) {
	amount, err := decimal(t.Amount)
	if err != nil {
		return transfer.Receipt{}, err
	}
	res, err := a.Legacy.TransferFunds(ctx, soapclient.TransferFundsRequest{
		FromAccount: t.From,
		ToAccount:   t.To,
		Amount:      amount,
		Currency:    t.Amount.Currency,
		Reference:   t.ID, // the legacy system de-duplicates on Reference
	})
	if err != nil {
		return transfer.Receipt{}, translate(err)
	}
	if res.Status != "00" {
		return transfer.Receipt{}, fmt.Errorf("%w: legacy status %s", transfer.ErrRejected, res.Status)
	}
	return transfer.Receipt{TransferID: t.ID, AuthCode: res.AuthCode}, nil
}

// translate maps legacy codes to domain errors; this is the whole point of the layer.
func translate(err error) error {
	var fe *soapclient.FaultError
	if !errors.As(err, &fe) {
		return fmt.Errorf("%w: %v", transfer.ErrUnavailable, err) // transport trouble is retryable
	}
	switch fe.Fault.Detail.ErrorCode {
	case "51":
		return transfer.ErrInsufficientFunds
	case "62":
		return transfer.ErrAccountRestricted
	case "91":
		return fmt.Errorf("%w: %s", transfer.ErrUnavailable, fe.Fault.String)
	default:
		return fmt.Errorf("%w: legacy code %s", transfer.ErrRejected, fe.Fault.Detail.ErrorCode)
	}
}

// decimal renders minor units as the decimal string the legacy contract wants.
func decimal(m transfer.Money) (string, error) {
	exp, ok := exponents[m.Currency]
	if !ok || m.Minor <= 0 {
		return "", fmt.Errorf("%w: unsupported amount %d %s", transfer.ErrRejected, m.Minor, m.Currency)
	}
	if exp == 0 {
		return fmt.Sprintf("%d", m.Minor), nil
	}
	pow := int64(1)
	for i := 0; i < exp; i++ {
		pow *= 10
	}
	return fmt.Sprintf("%d.%0*d", m.Minor/pow, exp, m.Minor%pow), nil
}

The same capability as a contract-first REST/JSON service ​

The contract is written first:

yaml
openapi: 3.1.0
info:
  title: Transfers API
  version: 1.0.0
  description: Contract-first REST/JSON facade over the transfer capability.
paths:
  /v1/transfers:
    post:
      operationId: createTransfer
      summary: Move money between two accounts.
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          schema: { type: string, maxLength: 64 }
          description: Same key, same answer. The key is also the transfer id.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateTransfer' }
      responses:
        '201':
          description: Transfer completed.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Transfer' }
        '200':
          description: Replay of an earlier request with the same key.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Transfer' }
        '422':
          description: Business rule failed (insufficient funds, rejected).
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '503':
          description: Downstream unavailable. Retry with the same key after Retry-After.
          headers:
            Retry-After: { schema: { type: integer } }
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
components:
  schemas:
    Money:
      type: object
      required: [minor, currency]
      properties:
        minor: { type: integer, minimum: 1, description: Minor units (cents). }
        currency: { type: string, pattern: '^[A-Z]{3}$' }
    CreateTransfer:
      type: object
      additionalProperties: false
      required: [from, to, amount]
      properties:
        from: { type: string }
        to: { type: string }
        amount: { $ref: '#/components/schemas/Money' }
    Transfer:
      type: object
      required: [id, status]
      properties:
        id: { type: string }
        status: { type: string, enum: [completed] }
        authCode: { type: string }
    Problem:
      type: object
      required: [type, title, status]
      properties:
        type: { type: string }
        title: { type: string }
        status: { type: integer }

The handler implements it on top of the domain port, so it does not care whether the port is the SOAP adapter or a future native service:

go
// Package restapi exposes the transfer capability as a contract-first
// REST/JSON service. The contract is contract/transfers.openapi.yaml.
package restapi

import (
	"encoding/json"
	"errors"
	"net/http"
	"sync"

	"academy/service-oriented-architecture/transfer"
)

type createTransfer struct {
	From   string `json:"from"`
	To     string `json:"to"`
	Amount struct {
		Minor    int64  `json:"minor"`
		Currency string `json:"currency"`
	} `json:"amount"`
}

type transferResource struct {
	ID       string `json:"id"`
	Status   string `json:"status"`
	AuthCode string `json:"authCode"`
}

// problem follows RFC 9457 (application/problem+json).
type problem struct {
	Type   string `json:"type"`
	Title  string `json:"title"`
	Status int    `json:"status"`
}

// Handler serves POST /v1/transfers on top of any transfer.Port.
type Handler struct {
	Port transfer.Port
	mu   sync.Mutex
	seen map[string]transferResource // Idempotency-Key -> first answer
}

// Routes registers the single operation of the contract.
func (h *Handler) Routes() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /v1/transfers", h.create)
	return mux
}

func (h *Handler) create(w http.ResponseWriter, r *http.Request) {
	key := r.Header.Get("Idempotency-Key")
	if key == "" {
		write(w, http.StatusBadRequest, "application/problem+json", problem{"/problems/missing-idempotency-key", "Idempotency-Key header is required", 400})
		return
	}
	h.mu.Lock()
	if prev, ok := h.seen[key]; ok {
		h.mu.Unlock()
		write(w, http.StatusOK, "application/json", prev) // replay, not a second transfer
		return
	}
	h.mu.Unlock()

	var in createTransfer
	dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<16))
	dec.DisallowUnknownFields()
	if err := dec.Decode(&in); err != nil {
		write(w, http.StatusBadRequest, "application/problem+json", problem{"/problems/invalid-body", "Invalid request body", 400})
		return
	}
	rc, err := h.Port.Transfer(r.Context(), transfer.Transfer{
		ID: key, From: in.From, To: in.To,
		Amount: transfer.Money{Minor: in.Amount.Minor, Currency: in.Amount.Currency},
	})
	if err != nil {
		st, p := mapError(err)
		if st == http.StatusServiceUnavailable {
			w.Header().Set("Retry-After", "5")
		}
		write(w, st, "application/problem+json", p)
		return
	}
	res := transferResource{ID: rc.TransferID, Status: "completed", AuthCode: rc.AuthCode}
	h.mu.Lock()
	if h.seen == nil {
		h.seen = map[string]transferResource{}
	}
	h.seen[key] = res
	h.mu.Unlock()
	write(w, http.StatusCreated, "application/json", res)
}

func mapError(err error) (int, problem) {
	switch {
	case errors.Is(err, transfer.ErrInsufficientFunds):
		return 422, problem{"/problems/insufficient-funds", "Insufficient funds", 422}
	case errors.Is(err, transfer.ErrAccountRestricted):
		return 403, problem{"/problems/account-restricted", "Account restricted", 403}
	case errors.Is(err, transfer.ErrUnavailable):
		return 503, problem{"/problems/unavailable", "Temporarily unavailable, retry with the same key", 503}
	default:
		return 422, problem{"/problems/rejected", "Transfer rejected", 422}
	}
}

func write(w http.ResponseWriter, status int, ct string, v any) {
	w.Header().Set("Content-Type", ct)
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

Notice the Idempotency-Key requirement. The legacy SOAP service identifies a transfer by its reference; the REST facade passes the key through as that reference. Retries by a client then become safe end to end, see API idempotency and idempotent consumers.

The Go angle ​

TopicGo approachNote
XMLencoding/xml structs with namespace tagsUnmarshal ignores unknown elements by default: tolerant reader
HTTP clientnet/http with http.Client{Timeout} and contextAlways set a timeout; the default client has none
Routinghttp.ServeMux with method patterns (POST /v1/transfers)No router library needed
Contract-firstGenerate server stubs from OpenAPI (oapi-codegen) or write by handKeep the YAML in the repo
SOAP librariesThird-party (gosoap, hooklift/gowsdl)Read the generated code before trusting it
Testinghttptest.NewServer and recorded envelopesOne test per fault code

Laravel ​

PHP ships with the SoapClient class in ext-soap. The manual says it "can be used in WSDL or non-WSDL mode"; in WSDL mode every operation becomes a method. Laravel's HTTP client is the alternative when you want its retries, fakes and logging, at the price of building the envelope yourself (Http::withBody($xml, 'text/xml') is the documented raw-body call).

The port and domain exceptions ​

php
<?php

declare(strict_types=1);

namespace App\Transfers;

/** What the application depends on. Neither SOAP nor HTTP appears here. */
interface TransferPort
{
    /** @throws InsufficientFunds|AccountRestricted|TransferUnavailable|TransferRejected */
    public function transfer(TransferRequest $request): Receipt;
}

final readonly class TransferRequest
{
    public function __construct(
        public string $id,        // idempotency key, also the legacy "reference"
        public string $from,
        public string $to,
        public int $amountMinor,  // minor units, never floats
        public string $currency,
    ) {}
}

final readonly class Receipt
{
    public function __construct(public string $transferId, public string $authCode) {}
}

class TransferException extends \RuntimeException {}
final class InsufficientFunds extends TransferException {}
final class AccountRestricted extends TransferException {}
final class TransferUnavailable extends TransferException {}   // retryable
final class TransferRejected extends TransferException {}

Consuming the WSDL with SoapClient, behind an anti-corruption layer ​

First the contract the legacy side publishes:

wsdl
<?xml version="1.0" encoding="UTF-8"?>
<!-- WSDL 1.1, document/literal wrapped: the contract of the legacy core-banking service. -->
<wsdl:definitions name="TransferService"
    targetNamespace="urn:example:bank:transfer:v1"
    xmlns:tns="urn:example:bank:transfer:v1"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
  <wsdl:types>
    <xsd:schema targetNamespace="urn:example:bank:transfer:v1" elementFormDefault="qualified">
      <xsd:element name="TransferFunds">
        <xsd:complexType><xsd:sequence>
          <xsd:element name="fromAccount" type="xsd:string"/>
          <xsd:element name="toAccount" type="xsd:string"/>
          <xsd:element name="amount" type="xsd:decimal"/>
          <xsd:element name="currency" type="xsd:string"/>
          <xsd:element name="reference" type="xsd:string"/>
        </xsd:sequence></xsd:complexType>
      </xsd:element>
      <xsd:element name="TransferFundsResponse">
        <xsd:complexType><xsd:sequence>
          <xsd:element name="status" type="xsd:string"/>
          <xsd:element name="authCode" type="xsd:string"/>
        </xsd:sequence></xsd:complexType>
      </xsd:element>
    </xsd:schema>
  </wsdl:types>
  <wsdl:message name="TransferFundsIn"><wsdl:part name="parameters" element="tns:TransferFunds"/></wsdl:message>
  <wsdl:message name="TransferFundsOut"><wsdl:part name="parameters" element="tns:TransferFundsResponse"/></wsdl:message>
  <wsdl:portType name="TransferPort">
    <wsdl:operation name="TransferFunds">
      <wsdl:input message="tns:TransferFundsIn"/>
      <wsdl:output message="tns:TransferFundsOut"/>
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="TransferSoapBinding" type="tns:TransferPort">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="TransferFunds">
      <soap:operation soapAction="urn:example:bank:transfer:v1/TransferFunds"/>
      <wsdl:input><soap:body use="literal"/></wsdl:input>
      <wsdl:output><soap:body use="literal"/></wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="TransferService">
    <wsdl:port name="TransferSoapPort" binding="tns:TransferSoapBinding">
      <soap:address location="https://core.bank.example/ws/transfer"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

Then the adapter:

php
<?php

declare(strict_types=1);

namespace App\Transfers;

use SoapClient;
use SoapFault;

/**
 * Anti-corruption layer: the only class that knows the legacy WSDL, decimal
 * strings and ISO-8583-style response codes. Everything else sees TransferPort.
 */
final class LegacyTransferAdapter implements TransferPort
{
    private const EXPONENTS = ['EUR' => 2, 'USD' => 2, 'JPY' => 0, 'KWD' => 3];

    public function __construct(private readonly SoapClient $soap) {}

    /** Build the client once; see config/services.php for the values. */
    public static function fromConfig(): self
    {
        return new self(new SoapClient(config('services.core_bank.wsdl'), [
            'soap_version'       => SOAP_1_1,
            'exceptions'         => true,           // failures become SoapFault
            'trace'              => false,
            'connection_timeout' => 3,              // connect timeout, seconds
            'cache_wsdl'         => WSDL_CACHE_DISK, // do not re-download the WSDL per request
        ]));
    }

    public function transfer(TransferRequest $request): Receipt
    {
        try {
            // Document/literal wrapped: one argument object per call.
            $response = $this->soap->TransferFunds([
                'fromAccount' => $request->from,
                'toAccount'   => $request->to,
                'amount'      => $this->decimal($request->amountMinor, $request->currency),
                'currency'    => $request->currency,
                'reference'   => $request->id,
            ]);
        } catch (SoapFault $fault) {
            throw $this->translate($fault);
        }

        if ($response->status !== '00') {
            throw new TransferRejected("legacy status {$response->status}");
        }

        return new Receipt($request->id, (string) $response->authCode);
    }

    private function translate(SoapFault $fault): TransferException
    {
        // The business code travels in <detail><ErrorCode>. Depending on the server's
        // WSDL, PHP exposes detail as an object or as a raw string; handle both.
        $detail = $fault->detail ?? null;
        $code = match (true) {
            is_object($detail) => (string) ($detail->ErrorCode ?? ''),
            is_string($detail) => preg_match('~<ErrorCode>(\w+)</ErrorCode>~', $detail, $m) ? $m[1] : '',
            default            => '',
        };

        return match ($code) {
            '51'    => new InsufficientFunds(),
            '62'    => new AccountRestricted(),
            '91', '' => new TransferUnavailable($fault->getMessage(), 0, $fault), // transport faults have no code
            default => new TransferRejected("legacy code {$code}", 0, $fault),
        };
    }

    private function decimal(int $minor, string $currency): string
    {
        $exp = self::EXPONENTS[$currency] ?? throw new TransferRejected("unsupported currency {$currency}");
        if ($minor <= 0) {
            throw new TransferRejected('amount must be positive');
        }
        $pow = 10 ** $exp;

        return $exp === 0
            ? (string) $minor
            : sprintf('%d.%0' . $exp . 'd', intdiv($minor, $pow), $minor % $pow);
    }
}

The same call through Laravel's HTTP client ​

php
<?php

declare(strict_types=1);

namespace App\Transfers;

use Illuminate\Support\Facades\Http;

/**
 * The same call without ext-soap: Laravel's HTTP client with a hand-built
 * SOAP 1.1 envelope. Useful when you want retries, timeouts, fakes and logging
 * from the HTTP client instead of SoapClient.
 */
final class RawSoapOverHttpClient
{
    private const NS = 'urn:example:bank:transfer:v1';

    public function transferFunds(TransferRequest $r, string $amountDecimal): \SimpleXMLElement
    {
        $xml = sprintf(
            '<?xml version="1.0" encoding="UTF-8"?>'
            . '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:t="%s">'
            . '<soapenv:Body><t:TransferFunds><t:fromAccount>%s</t:fromAccount><t:toAccount>%s</t:toAccount>'
            . '<t:amount>%s</t:amount><t:currency>%s</t:currency><t:reference>%s</t:reference></t:TransferFunds>'
            . '</soapenv:Body></soapenv:Envelope>',
            self::NS,
            htmlspecialchars($r->from, ENT_XML1), htmlspecialchars($r->to, ENT_XML1),
            $amountDecimal, htmlspecialchars($r->currency, ENT_XML1), htmlspecialchars($r->id, ENT_XML1),
        );

        $response = Http::withBody($xml, 'text/xml; charset=utf-8')
            ->withHeaders(['SOAPAction' => '"' . self::NS . '/TransferFunds"'])
            ->timeout(5)
            ->retry(2, 200, throw: false) // safe only because the legacy side de-duplicates on <reference>
            ->post(config('services.core_bank.endpoint'));

        // SOAP 1.1 faults arrive as HTTP 500 with a body, so parse before judging the status.
        $doc = simplexml_load_string($response->body());
        if ($doc === false) {
            throw new TransferUnavailable('legacy answered with a non-XML body, HTTP ' . $response->status());
        }

        return $doc;
    }
}

Exposing a REST/JSON contract ​

php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Transfers\AccountRestricted;
use App\Transfers\InsufficientFunds;
use App\Transfers\TransferPort;
use App\Transfers\TransferRejected;
use App\Transfers\TransferRequest;
use App\Transfers\TransferUnavailable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

/** Contract-first REST/JSON facade; shape defined by contract/transfers.openapi.yaml. */
final class TransferController
{
    public function __construct(private readonly TransferPort $transfers) {}

    public function store(Request $request): JsonResponse
    {
        $key = $request->header('Idempotency-Key');
        if ($key === null || $key === '') {
            return $this->problem(400, 'missing-idempotency-key', 'Idempotency-Key header is required');
        }

        $data = $request->validate([
            'from'            => ['required', 'string'],
            'to'              => ['required', 'string'],
            'amount.minor'    => ['required', 'integer', 'min:1'],
            'amount.currency' => ['required', 'string', 'size:3'],
        ]);

        // Replay: the same key returns the first answer and calls nobody.
        if ($first = Cache::get("transfer:$key")) {
            return response()->json($first, 200);
        }

        try {
            $receipt = $this->transfers->transfer(new TransferRequest(
                $key, $data['from'], $data['to'], $data['amount']['minor'], $data['amount']['currency'],
            ));
        } catch (InsufficientFunds) {
            return $this->problem(422, 'insufficient-funds', 'Insufficient funds');
        } catch (AccountRestricted) {
            return $this->problem(403, 'account-restricted', 'Account restricted');
        } catch (TransferUnavailable) {
            return $this->problem(503, 'unavailable', 'Temporarily unavailable, retry with the same key')
                ->header('Retry-After', '5');
        } catch (TransferRejected) {
            return $this->problem(422, 'rejected', 'Transfer rejected');
        }

        $body = ['id' => $receipt->transferId, 'status' => 'completed', 'authCode' => $receipt->authCode];
        Cache::put("transfer:$key", $body, now()->addDay());

        return response()->json($body, 201);
    }

    private function problem(int $status, string $type, string $title): JsonResponse
    {
        return response()->json(
            ['type' => "/problems/$type", 'title' => $title, 'status' => $status],
            $status,
            ['Content-Type' => 'application/problem+json'],
        );
    }
}
php
<?php

declare(strict_types=1);

use App\Http\Controllers\TransferController;
use App\Transfers\LegacyTransferAdapter;
use App\Transfers\TransferPort;
use Illuminate\Support\Facades\Route;

// routes/api.php: the SOAP service is hidden behind the port.
// In a service provider: $this->app->bind(TransferPort::class, fn () => LegacyTransferAdapter::fromConfig());
Route::post('/v1/transfers', [TransferController::class, 'store'])->middleware('throttle:60,1');

// config/services.php:
// 'core_bank' => ['wsdl' => env('CORE_BANK_WSDL'), 'endpoint' => env('CORE_BANK_ENDPOINT')],

The Laravel angle ​

TopicLaravel 13 / PHP 8.4 approachNote
SOAP clientSoapClient (ext-soap), SOAP_1_1, exceptions => true, connection_timeout, cache_wsdlCatch SoapFault; wrap in domain exceptions
SOAP over HTTPHttp::withBody(), withHeaders(), timeout(), retry()Fake in tests with Http::fake()
SOAP serverNot built in; use SoapServer or a package, or avoid itDo not add SOAP to a new system
Port binding$this->app->bind(TransferPort::class, ...) in a providerSwap adapter for a native service later
Validation$request->validate([...]) with dotted keysMatches the OpenAPI schema
IdempotencyCache::get/Cache::put keyed by header, or a database unique keyUse the database for money
OrchestrationA service class or Bus::chain() plus a process tableSee worked example
ChoreographyEvents and queued listeners, ideally with a brokerSee outbox

Worked example: a bank transfer, two ways ​

A customer moves 125.50 EUR from account A to B. Capabilities: fraud check, debit, credit, notification. The same business operation in both styles.

SOA style: one orchestrator ​

go
// Package orchestrator is the SOA-style transfer: one central process owns the
// flow, calls each service in order and compensates in reverse on failure.
package orchestrator

import (
	"context"
	"errors"
	"fmt"
)

// Services are the capabilities the orchestrator composes.
type Services interface {
	CheckFraud(ctx context.Context, transferID string, minor int64) error
	Debit(ctx context.Context, transferID, account string, minor int64) error
	Credit(ctx context.Context, transferID, account string, minor int64) error
	Refund(ctx context.Context, transferID, account string, minor int64) error
	Notify(ctx context.Context, transferID string) error
}

// Store persists the process state so a crashed orchestrator can resume.
type Store interface {
	Save(ctx context.Context, transferID, state string) error
}

// Orchestrator holds the whole business flow in one place.
type Orchestrator struct {
	Svc   Services
	State Store
}

// Run executes the transfer. Every step is logged to the store first.
func (o *Orchestrator) Run(ctx context.Context, id, from, to string, minor int64) error {
	step := func(state string, fn func() error) error {
		if err := o.State.Save(ctx, id, state); err != nil {
			return err
		}
		return fn()
	}
	if err := step("FRAUD_CHECK", func() error { return o.Svc.CheckFraud(ctx, id, minor) }); err != nil {
		_ = o.State.Save(ctx, id, "REJECTED")
		return fmt.Errorf("fraud: %w", err)
	}
	if err := step("DEBITING", func() error { return o.Svc.Debit(ctx, id, from, minor) }); err != nil {
		_ = o.State.Save(ctx, id, "FAILED")
		return fmt.Errorf("debit: %w", err)
	}
	if err := step("CREDITING", func() error { return o.Svc.Credit(ctx, id, to, minor) }); err != nil {
		// Compensation: undo the debit. This line is the saga, written as code.
		if rerr := o.Svc.Refund(ctx, id, from, minor); rerr != nil {
			_ = o.State.Save(ctx, id, "NEEDS_MANUAL_REVIEW")
			return errors.Join(fmt.Errorf("credit: %w", err), fmt.Errorf("refund: %w", rerr))
		}
		_ = o.State.Save(ctx, id, "COMPENSATED")
		return fmt.Errorf("credit: %w", err)
	}
	_ = o.State.Save(ctx, id, "COMPLETED")
	_ = o.Svc.Notify(ctx, id) // best effort: a failed email must not undo money
	return nil
}
php
<?php

declare(strict_types=1);

namespace App\Transfers;

use Illuminate\Support\Facades\DB;

/**
 * SOA style: one orchestrator owns the flow, persists its state in a process
 * table and compensates in reverse order. The services below are plain interfaces.
 */
final class OrchestratedTransfer
{
    public function __construct(
        private readonly FraudService $fraud,
        private readonly AccountsService $accounts,
        private readonly NotificationService $notifications,
    ) {}

    public function run(string $id, string $from, string $to, int $minor): void
    {
        $state = fn (string $s) => DB::table('transfer_process')->updateOrInsert(
            ['transfer_id' => $id], ['state' => $s, 'updated_at' => now()],
        );

        $state('FRAUD_CHECK');
        $this->fraud->check($id, $minor);              // throws on reject

        $state('DEBITING');
        $this->accounts->debit($id, $from, $minor);

        $state('CREDITING');
        try {
            $this->accounts->credit($id, $to, $minor);
        } catch (\Throwable $e) {
            $this->accounts->refund($id, $from, $minor); // compensation, same idempotency key
            $state('COMPENSATED');
            throw $e;
        }

        $state('COMPLETED');
        rescue(fn () => $this->notifications->send($id)); // best effort, never undoes money
    }
}

interface FraudService { public function check(string $id, int $minor): void; }
interface AccountsService
{
    public function debit(string $id, string $account, int $minor): void;
    public function credit(string $id, string $account, int $minor): void;
    public function refund(string $id, string $account, int $minor): void;
}
interface NotificationService { public function send(string $id): void; }

The orchestrator persists its state before each step so a crash resumes instead of repeating or forgetting:

sql
CREATE TABLE transfer_process (
    transfer_id  text        PRIMARY KEY,           -- also the idempotency key
    state        text        NOT NULL,              -- FRAUD_CHECK, DEBITING, CREDITING, COMPLETED, COMPENSATED, NEEDS_MANUAL_REVIEW
    updated_at   timestamptz NOT NULL DEFAULT now()
);
-- A recovery job resumes anything stuck for more than a minute.
SELECT transfer_id, state FROM transfer_process
WHERE state IN ('DEBITING', 'CREDITING') AND updated_at < now() - interval '1 minute'
FOR UPDATE SKIP LOCKED;
 1  Client     -> Orchestrator: TransferFunds(t1, A, B, 125.50)
 2  Orchestrator -> Fraud:       check(t1)            OK
 3  Orchestrator -> Accounts:    debit(t1, A)         OK   state=DEBITING
 4  Orchestrator -> Accounts:    credit(t1, B)        FAIL beneficiary closed
 5  Orchestrator -> Accounts:    refund(t1, A)        OK   state=COMPENSATED
 6  Orchestrator -> Client:      error: beneficiary closed

Microservice style: choreography ​

go
// Package choreography is the microservice-style transfer: no central brain.
// Each service reacts to events and publishes its own; the bus is dumb.
package choreography

import "sync"

// Event is a fact that already happened.
type Event struct {
	Name       string // for example "TransferRequested"
	TransferID string
	Minor      int64
}

// Bus is a synchronous in-memory pipe. A real system uses a broker such as
// RabbitMQ or Kafka, and then delivery is asynchronous and at-least-once.
type Bus struct {
	mu   sync.Mutex
	subs map[string][]func(Event)
	Log  []string
}

// Subscribe registers a handler for one event name.
func (b *Bus) Subscribe(name string, h func(Event)) {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.subs == nil {
		b.subs = map[string][]func(Event){}
	}
	b.subs[name] = append(b.subs[name], h)
}

// Publish delivers to every subscriber and records the event name.
func (b *Bus) Publish(e Event) {
	b.mu.Lock()
	b.Log = append(b.Log, e.Name)
	hs := append([]func(Event){}, b.subs[e.Name]...)
	b.mu.Unlock()
	for _, h := range hs {
		h(e)
	}
}

// Wire connects three services. Nobody owns the flow; it emerges from who
// listens to what. Funds is a stand-in for the accounts service.
func Wire(b *Bus, fraudOK func(Event) bool, debit func(Event) bool) {
	// Fraud service: TransferRequested -> TransferApproved | TransferRejected.
	b.Subscribe("TransferRequested", func(e Event) {
		if fraudOK(e) {
			b.Publish(Event{"TransferApproved", e.TransferID, e.Minor})
			return
		}
		b.Publish(Event{"TransferRejected", e.TransferID, e.Minor})
	})
	// Accounts service: TransferApproved -> FundsDebited | DebitFailed.
	b.Subscribe("TransferApproved", func(e Event) {
		if debit(e) {
			b.Publish(Event{"FundsDebited", e.TransferID, e.Minor})
			return
		}
		b.Publish(Event{"DebitFailed", e.TransferID, e.Minor})
	})
	// Notification service: reacts to the facts it cares about.
	b.Subscribe("FundsDebited", func(e Event) { b.Publish(Event{"CustomerNotified", e.TransferID, 0}) })
	b.Subscribe("DebitFailed", func(e Event) { b.Publish(Event{"CustomerNotified", e.TransferID, 0}) })
}
php
<?php

declare(strict_types=1);

namespace App\Transfers\Choreography;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Events\Dispatchable;
use App\Transfers\AccountsService;

/** Microservice style: no orchestrator. Each service owns one reaction. */
final readonly class TransferRequested { use Dispatchable; public function __construct(public string $id, public string $from, public int $minor) {} }
final readonly class TransferApproved  { use Dispatchable; public function __construct(public string $id, public string $from, public int $minor) {} }
final readonly class FundsDebited      { use Dispatchable; public function __construct(public string $id, public int $minor) {} }
final readonly class DebitFailed       { use Dispatchable; public function __construct(public string $id) {} }

/** Lives in the fraud service. */
final class ApproveTransfer implements ShouldQueue
{
    public function handle(TransferRequested $e): void
    {
        if ($e->minor <= 1_000_000) {
            TransferApproved::dispatch($e->id, $e->from, $e->minor);
        }
    }
}

/** Lives in the accounts service. Must be idempotent: queues deliver at least once. */
final class DebitAccount implements ShouldQueue
{
    public function handle(TransferApproved $e): void
    {
        $accounts = app(AccountsService::class);
        try {
            $accounts->debit($e->id, $e->from, $e->minor);
            FundsDebited::dispatch($e->id, $e->minor);
        } catch (\Throwable) {
            DebitFailed::dispatch($e->id);
        }
    }
}

// In a service provider's boot():
// Event::listen(TransferRequested::class, ApproveTransfer::class);
// Event::listen(TransferApproved::class, DebitAccount::class);
 1  Payments  publishes TransferRequested(t1)
 2  Fraud     consumes, publishes TransferApproved(t1)
 3  Accounts  consumes, debits A, publishes FundsDebited(t1)
 4  Accounts  (credit side) consumes, credit fails, publishes CreditFailed(t1)
 5  Accounts  consumes its own CreditFailed, refunds A, publishes FundsRefunded(t1)
 6  Notify    consumes FundsRefunded, tells the customer

Trade-offs ​

QuestionOrchestrated (SOA)Choreographed (microservices)
Where is the business flow written?One class and one tableSpread over four listeners
Adding "AML check after fraud"Edit the orchestrator, redeploy itNew service subscribes to TransferApproved, publishes its own event; fraud and accounts must agree on ordering
Debugging a stuck transferSELECT from transfer_processCorrelate events across services with a trace id
Failure of the orchestratorTransfers pause; recovery job resumesNo central part to fail; each service retries its inbox
CouplingOrchestrator knows every service's APIServices know event schemas
OwnershipPlatform or integration team owns the flowEach team owns its reaction
Delivery guarantee neededReliable call plus persisted stateAt-least-once events, idempotent consumers, outbox
Good fitFew steps, strong audit, regulated flowMany teams, many reactions, evolving flow

Honest recommendation: for a regulated money movement, keep the flow in one place (a small orchestrator or workflow engine with an audit table) and use events for the reactions that do not decide the outcome (notifications, analytics, search indexing). That hybrid is what most mature systems end up with; see saga pattern.

Mechanics: what a call really goes through ​

Message anatomy ​

PartSOAP 1.1REST/JSON
Operation nameSOAPAction header and body elementHTTP method plus URL
PayloadBody with a typed elementJSON document
MetadataHeader blocks (security, addressing, correlation)HTTP headers
ErrorFault with faultcode, faultstring, detail (HTTP 500)HTTP status plus problem+json
TypingXSDJSON Schema in OpenAPI
Service descriptionWSDL (types, message, portType, binding, service)OpenAPI document
CachingNone (POST)GET with ETag, Cache-Control
Retry safetyProvider-defined; use a reference fieldIdempotency-Key, PUT

Error codes and what to do ​

WhereSignalMeaningRetry?
SOAPfaultcode Client (1.1)Your message is wrongNo
SOAPfaultcode Server (1.1)Provider failedMaybe, if idempotent
SOAPdetail/ErrorCode 51Insufficient funds (our example)No
SOAPdetail/ErrorCode 91Authoriser unavailableYes, same reference
HTTP503 plus Retry-AfterOverloaded or maintenanceYes, same key
HTTPTimeout, connection resetUnknown outcomeYes, only with idempotency
REST facade422 problem+jsonBusiness rejectionNo
REST facade200 on replaySame key seen beforeNot needed

Solving the classic problems ​

ProblemSolutionHowCost
ESB as a bottleneckMove logic to services, keep a thin gatewayGateway: auth, quotas, routing onlyServices must own validation
Canonical model deadlockPer-context models plus anti-corruption layersTranslate at each boundaryMore mapping code, explicit
No distributed transactionSaga with compensationOrchestrator or events; sagaEventual consistency, UX for pending states
Duplicate calls after timeoutIdempotency key as legacy referenceOne id for the whole chainKey storage, expiry policy
Legacy SOAP spreadsAnti-corruption layerDomain port, one adapterOne more layer to test
Contract driftContract tests, recorded envelopesReplay fixtures in CIMaintenance of fixtures
Shared reusable service blocks teamsCopy-then-extract, or consumer-driven contractsLet teams own a sliceSome duplication
Orchestrator crashPersist state, recovery jobtransfer_process tableA process table to operate
Message loss between servicesOutbox plus at-least-once, idempotent consumerOutboxDelay, duplicates handled
Slow SOAP providerTimeout, circuit breaker, bulkheadcontext timeouts, breaker libraryDegraded features

Choosing ​

SituationRecommendationTechniqueWhy
New product, one teamModular monolithInternal portsCheapest; see modular monolith
10 to 50 engineers, clear domainsService-based architecture4 to 12 domain servicesIndependent deploys without microservice cost
Many teams, independent scaling needsMicroservicesDumb pipes, event contractsTeam autonomy; see microservices
Must consume a bank's SOAP APIAnti-corruption layerPort plus adapterKeeps legacy out of the domain
Integrating 20 existing packaged systemsIntegration platform or ESB-like productCamel, MuleSoft, iPaaS; logic stays in systemsLegitimate ESB use: connect, do not decide
Regulated multi-step flowOrchestrated workflow with auditTemporal, Camunda, or a process tableOne place to prove what happened
Many reactions to an eventChoreographyBroker and idempotent consumersTeams add reactions without a release
Public API for partnersREST/JSON with OpenAPIGateway, quotas, versioningReach and tooling

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

Service orientation here is a design discipline: modules expose a small interface (TransferPort) and hide their tables. Example: the transfer module of a Laravel monolith binds TransferPort to an Eloquent-based adapter; callers never touch the accounts table. If one day the capability moves behind SOAP or HTTP, only the adapter changes. Do not introduce a bus, a canonical model or an orchestrator at this size.

Modular monolith / multiple databases ​

Each module owns its schema and publishes in-process events (see modular monolith). A legacy SOAP provider is wrapped once by an ACL module. Example: the payments module calls the core-banking WSDL through LegacyTransferAdapter; the ledger module records the result in its own schema within one local transaction. Service-based architecture is the next step: extract payments as a deployable service that still shares the operational database for a while.

Microservices ​

Capabilities become independent services with their own data. Example flow across services: the web BFF calls payments, which calls fraud (HTTP, 300 ms timeout) and publishes TransferRequested through an outbox; accounts debits and credits using idempotency keys; a saga (orchestrated by payments or choreographed) handles failure. The SOA lessons that matter here: keep the pipe dumb, put the contract in the repo, never share a database, and keep a canonical model only for industry-standard messages. Details in service boundaries and data ownership.

Distributed data (replicas, caches, multi-region) ​

A SOAP call to the system of record is a synchronous dependency; replicas and caches in front of it return stale balances. Example: the mobile app reads the balance from a read replica of the ledger view, fed by events from the system of record; the transfer itself always goes to the primary. Money movement stays strongly consistent inside the system of record; everything around it is eventually consistent, and the UI shows "pending" until the confirming event arrives. See replication and distributed SQL.

Scaling path ​

LoadDesignNotes
1x: 10 transfers per minuteMonolith, one TransferPort, SOAP adapter insideTimeouts and idempotency from day one
10x: 100 per minuteQueue the SOAP calls, workers with limited concurrencyThe legacy system's capacity is the ceiling; respect it
100x: 1,000 per minuteExtract payments service, outbox, saga, rate-limited ACLGateway quotas protect the legacy provider
1,000x and many teamsPer-domain services, events, schema registry, workflow engine for regulated flowsRetire the SOAP adapter with the strangler fig when the core is replaced

Lab ​

Exercise: run the SOAP client, anti-corruption layer and REST facade against a fake legacy server and watch idempotency work.

  1. Run the tests that already contain the fake legacy provider:
bash
cd docs/snippets/architecture/service-oriented-architecture/go
go test ./... -v
# expected: soapclient TestSuccess and TestFaultOnHTTP500 pass; acl TestFaultMapping passes
  1. Break the contract on purpose: in soapclient/client_test.go rename the fromAccount element in the fixture and run again. Expected: the server-side assertion fails, which is how contract drift is caught.
  2. Change the fault code from 51 to 91: expected result ErrUnavailable. Write a test proving the REST handler answers 503 with Retry-After.
  3. Send the same POST /v1/transfers twice with one Idempotency-Key: expected 201 then 200, and the fake port counts one call (see restapi/handler_test.go).
  4. Run the orchestrator test (orchestrator_test.go): credit fails, state ends COMPENSATED, last call is refund.
  5. Extend the choreography test with a fraud rejection and write down the event log; then answer: which team would be woken at 3 a.m. if CustomerNotified never appears?

Common misconceptions ​

BeliefReality
SOA is SOAPOASIS defines SOA as a paradigm; SOAP was one common implementation
An ESB is a message brokerA broker moves messages; an ESB also mediates, transforms and orchestrates
Microservices are small SOA servicesThe differences are data ownership, pipe intelligence and governance, not size
Reuse justifies every serviceReuse is found after the third consumer, not designed up front
A canonical model reduces couplingIt couples every system to one schema owned by a committee
WSDL generated from code is contract-firstContract-first means the contract is written before the code
Wrapping a monolith in services gives agilityThe release cycle stays tied to the monolith
SOAP is deadBanks, governments, ERP and telecom still publish SOAP; you must integrate cleanly
Choreography is always better than orchestrationRegulated flows often want one place that can prove what happened
UDDI is how discovery works todayIt was not widely adopted; catalogues and discovery systems replaced it

Cheat sheet ​

TopicWhat to remember
DefinitionOASIS: a paradigm for organising distributed capabilities under different ownership domains
Core ideaServices with published contracts and loose coupling
Eight principlesContract, loose coupling, abstraction, reusability, autonomy, statelessness, discoverability, composability
Four service typesBusiness, enterprise, application, infrastructure
ESBMediation, routing, transformation, orchestration; smart pipe
Orchestration vs choreographyCentral conductor vs reacting dancers
WS-*SOAP, WSDL, UDDI, WS-Security, WS-ReliableMessaging; heavy
SOAP 1.1 faultArrives as HTTP 500 with a Fault body
Canonical modelCheap at 6 systems (12 vs 30 translators), expensive to govern
GovernanceCentral boards slowed change; use guardrails
MicroservicesSmart endpoints, dumb pipes, database per service
Service-based4 to 12 coarse services, often shared database
Legacy SOAPWrap in an anti-corruption layer; integer money inside
IdempotencyOne id from edge to legacy reference
What survivesContract-first, API management, EIP, workflow engines

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What does the OASIS reference model say SOA is, and what does it say it does not cover? Good to know ​

Answer

Answer: A paradigm for organising and utilising distributed capabilities that may be under different ownership domains. It does not address orchestration of multiple services; orchestration and choreography belong to the process model, not the definition.

2 — Name the four service types of orchestration-driven SOA and one example each. Good to know ​

Answer

Answer: Business (TransferFunds), enterprise (GetBalance), application (a mainframe wrapper), infrastructure (audit, authentication).

3 — What is the difference between an ESB and a message broker? Must-know ​

Answer

Answer: A broker transports messages and stays dumb; an ESB also mediates, routes by content, transforms formats and may run orchestration and business rules.

4 — Why does a SOAP 1.1 client have to parse the body before checking the HTTP status? Good to know ​

Answer

Answer: SOAP 1.1 faults are sent with HTTP 500 and a Fault element; the status alone loses the faultcode and detail.

5 — How many translators do 6 applications need with and without a canonical data model? Important ​

Answer

Answer: 30 without, 12 with (Enterprise Integration Patterns arithmetic: N×(N−1) versus 2N).

6 — Give three reasons the WS-* stack was heavy. Good to know ​

Answer

Answer: Verbose XML and namespaces; many stacked specifications with vendor-specific extensions; tool-specific code generation and duplicated transport security.

7 — What is "smart endpoints and dumb pipes"? Must-know ​

Answer

Answer: Fowler's description of the microservice approach: logic lives in services, communication is plain HTTP or a simple broker; the opposite of putting routing, transformation and rules in an ESB.

8 — When is service-based architecture a better choice than microservices? Important ​

Answer

Answer: For medium systems and teams that need independent deployment of a few domains without the operational cost of many services and one database per service.

9 — Why should a legacy SOAP provider sit behind an anti-corruption layer? Important ​

Answer

Answer: To keep its data formats, codes and faults out of the domain; the adapter translates once, and the legacy system can later be replaced by changing only the adapter.

10 — In the transfer example, what does the orchestrator do when credit fails after debit succeeded? Important ​

Answer

Answer: It calls refund with the same transfer id (compensation), records COMPENSATED, and returns the error; if refund also fails it records NEEDS_MANUAL_REVIEW.

Glossary ​

TermMeaning
SOAService-Oriented Architecture: organising capabilities as services with published contracts
ServiceMechanism to access a capability through a prescribed interface (OASIS)
Service contractMachine-readable description of operations, messages and policy
SOAPXML messaging framework with envelope, header, body, fault
WSDLXML description of operations, messages, bindings and addresses
XSDXML Schema Definition, the type system of SOAP messages
UDDIRegistry specification for publishing and finding services
WS-SecurityOASIS spec for signing and encrypting SOAP messages
WS-ReliableMessagingOASIS spec for reliable delivery between SOAP endpoints
WS-*Family of specifications stacked on SOAP
ESBEnterprise Service Bus: central mediation, routing, transformation layer
MediationIntermediary between consumer and provider
OrchestrationCentral process that calls services in order
ChoreographyServices coordinating through events, no central owner
BPELXML language for orchestrating web services
Canonical data modelShared enterprise message vocabulary
Anti-corruption layerAdapter that translates a foreign model into the domain's
Service-based architectureFew coarse domain services, often a shared database
Smart pipesMiddleware holding routing and business logic
Dumb pipesTransport that only moves messages
Contract-firstWrite the contract before the implementation
Idempotency keyId making a repeated request produce the same result
CompensationAction that semantically undoes an earlier step
Strangler figGradual replacement of a legacy system behind a facade
API managementGateway, quotas, portal and versioning for APIs

References ​

Built by Morteza Negahi