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 for | Go to |
|---|---|
| The whole chapter in a few tables | Everything in one minute |
| Why SOA appeared and why people stopped saying it | Why it exists |
| CORBA, DCOM, web services, ESB, microservices | Where it comes from |
| The eight principles, one block each | Principles |
| Business / enterprise / application / infrastructure services | Service taxonomy |
| ESB, mediation, orchestration engine, BPEL | ESB and orchestration |
| SOAP, WSDL, UDDI, WS-Security, WS-ReliableMessaging | The WS-* stack |
| Canonical data model and what it costs | Canonical data model |
| Governance, reuse, "the SOA that failed" | Governance and reuse myths |
| SOA vs microservices table | SOA vs microservices |
| Service-based architecture (the middle way) | Service-based architecture |
| What survived | Where SOA ideas survive |
| Calling a SOAP endpoint from Go and Laravel | Legacy integration, Go, Laravel |
| Orchestrated vs choreographed bank transfer | Worked example |
| Monolith to distributed system | In architecture |
| Hands-on exercise | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked below.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Service | A capability reachable through a published interface | TransferFunds over SOAP | Consumers reach into internals |
| Service contract | The machine-readable promise of the interface | A WSDL file or an OpenAPI file | Everyone guesses the message format |
| SOAP | XML envelope protocol for messages | Envelope / Header / Body | Every integration invents its own wire format |
| WSDL | XML description of operations, messages, binding, address | legacy-transfer.wsdl | No generated clients, no checking |
| UDDI | A registry to publish and find services | Public "yellow pages" of services | Nobody knows what exists (and it was still not adopted) |
| WS-* | Add-on specs: security, reliability, policy, addressing | WS-Security signature in a header | Each vendor extends SOAP differently |
| ESB | A central bus doing mediation, routing, transformation | Mule, IBM Integration Bus, Oracle Service Bus | Point-to-point spaghetti (and, if misused, a new single brain) |
| Orchestration | One central process calls services in order | A BPEL process for "open account" | Business flow is scattered across callers |
| Choreography | Services react to each other's events, no centre | TransferApproved triggers debit | The centre becomes the bottleneck |
| Canonical data model | One shared enterprise message vocabulary | A global Customer schema | N-by-N translators between systems |
| Service-based architecture | A few coarse services, often one shared database | 4-12 domain services plus one UI | Microservices cost without the need |
SOA in one picture of trade-offs.
| You gain | You pay |
|---|---|
| Reuse of capabilities across applications | A central team and a queue in front of every change |
| Interoperability between Java, .NET, mainframe | Heavy XML, heavy tooling, heavy specs |
| One place for security, logging, routing | A single point of failure and of blame |
| Legacy systems become callable | Wrappers that freeze legacy behaviour |
The four service types (Richards & Ford, orchestration-driven SOA):
| Type | Granularity | Owner | Example |
|---|---|---|---|
| Business service | Coarse, entry point | Business analysts + architects | TransferFunds |
| Enterprise service | Fine, shared, reusable | Shared-services team | GetBalance, CreateCustomer |
| Application service | One application only | That application's team | MainframeWrapper.Post |
| Infrastructure service | Cross-cutting | Platform team | Audit, 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 integration | Service-oriented integration |
|---|---|
| Each pair agrees a private format | Each service publishes one contract |
| Adding application N+1 means N new links | Adding it means one new contract (in theory) |
| Knowledge of internals leaks | Consumers see only the interface |
| Cheap for 3 systems, chaos for 30 | Overhead 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
- "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.
- "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".
- "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
Customerservice.
Where it comes from
The timeline above is the story in five boxes. The details, with the reading status of each claim:
| Period | What happened | How we know |
|---|---|---|
| Early 1990s | CORBA (OMG) and DCOM (Microsoft) offer remote objects: call a method on an object in another process or machine | Secondary knowledge (Fowler's "CORBA with angle brackets" jab confirms the lineage); original specs not read |
| 8 May 2000 | SOAP 1.1 published as a W3C Note | Read: the SOAP 1.2 spec cites http://www.w3.org/TR/2000/NOTE-SOAP-20000508/ |
| August 2000 | UDDI written, with a vision of public service brokers | Wikipedia (secondary) |
| 15 March 2001 | WSDL 1.1 published as a W3C Note | Read: the Note's front page |
| 27 April 2007 | SOAP 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 2007 | WSDL 2.0 is a W3C Recommendation | Read |
| 2005 | Fowler: "SOA means so many different things to different people" | Read |
| January 2006 | IBM, Microsoft and SAP close their public UDDI nodes | Wikipedia (secondary) |
| 12 October 2006 | OASIS publishes the SOA Reference Model 1.0 | Read |
| 25 March 2014 | Fowler and Lewis publish the microservices article, with a Microservices and SOA section | Read |
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: callaccount.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 concept | Meaning | Where it shows up in practice |
|---|---|---|
| Visibility | Provider and consumer can see each other (awareness, willingness, reachability) | Registry, API portal, DNS name |
| Interaction | Using a capability through messages, with a real-world effect | An HTTP call that moves money |
| Real-world effect | Observable result of an interaction | Balance changes |
| Service description | Information needed to use the service | WSDL, OpenAPI |
| Contract and policy | What both sides agree to, plus conditions | Rate limit, authentication, SLA |
| Execution context | What is needed for interaction to happen | Security 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).
| Principle | Test question | Failing example | Modern equivalent |
|---|---|---|---|
| Standardized contract | Can I generate a client without talking to the team? | Contract is a Word document | OpenAPI, protobuf, WSDL |
| Loose coupling | Can the provider change language or database without me noticing? | Shared database table | Versioned API |
| Abstraction | Do I know only the capability, not the internals? | Error text exposes SQL | RFC 9457 problem types |
| Reusability | Does a second consumer use it unchanged? | One-off field added per consumer | Stable public API |
| Autonomy | Can it deploy and fail alone? | Needs the ESB to start | Independent deploy |
| Statelessness | Can any instance answer? | Sticky session | Token plus store |
| Discoverability | Can a newcomer find it in 5 minutes? | Wiki page from 2011 | API catalogue |
| Composability | Can it be one step of a bigger flow? | Operation returns a UI fragment | Idempotent operations |
Service taxonomy: business, enterprise, application, infrastructure
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:
| Layer | Role | Owned by | Example (bank) | Typical problem |
|---|---|---|---|---|
| Business services | Entry points; just a name and an input/output, little or no code | Business + architects | TransferFunds, OpenAccount | They are empty shells; real logic lives in the orchestrator |
| Enterprise services | Fine-grained, shared, "atomic" building blocks | Shared-services team | GetBalance, ValidateIban, CreateCustomer | Everyone depends on them, so nobody can change them |
| Application services | Specific to one application, not shared | One application team | PostLedgerEntry for the core banking system | Duplicates enterprise services |
| Infrastructure services | Cross-cutting plumbing | Platform team | Authentication, audit, monitoring | Often 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 portalEight 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 capability | What it does | Example | Risk |
|---|---|---|---|
| Mediation | Sits between consumer and provider, hides the endpoint | Consumer calls a virtual address | The bus becomes a mandatory hop |
| Routing | Chooses the destination by content, rules, version | Domestic vs international transfer route | Routing rules become business logic |
| Transformation | Converts formats (XML, fixed-width, JSON) via XSLT or mapping | Canonical Transfer to mainframe record | Mappings nobody can test |
| Protocol bridging | HTTP to JMS to FTP to MQ | SOAP in, MQ out | Hidden retries and timeouts |
| Orchestration | Runs a process definition (BPEL, BPMN) over services | Open account: KYC, create, notify | The centre owns all business flow |
| Security policy | Applies WS-Security, token mapping, throttling | Verify signature once | Single point of attack |
| Monitoring and audit | One place to log every call | Central audit trail | Log 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
Analogy: a conductor tells each musician when to play (orchestration); dancers at a ballroom each know the music and react to their neighbours (choreography).
| Property | Orchestration | Choreography |
|---|---|---|
| Who knows the whole flow | The orchestrator | Nobody; it emerges |
| Coupling | Services know nothing of each other; orchestrator knows all | Services know the events they react to |
| Failure handling | Compensation in one place | Each service compensates its own part |
| Visibility | Read one process definition | Needs tracing and event catalogue |
| Change | Edit one flow; the centre is a team bottleneck | Edit one service; risk of surprising consumers |
| Typical style | SOA with BPEL or an ESB | Microservices with events |
| Detail | Saga pattern | Event-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.
| Specification | Purpose | Standards body and version we read | Why it adds weight |
|---|---|---|---|
| SOAP | Envelope, header, body, fault, processing model | W3C SOAP 1.2 Part 1, Second Edition, 27 April 2007 | Verbose XML, namespaces on every element |
| WSDL | Describe operations, messages, bindings, addresses | W3C WSDL 1.1 Note (2001); WSDL 2.0 Recommendation (2007) | Large documents, code generators differ |
| XML Schema (XSD) | Message types | W3C | Complex type system, versioning pain |
| UDDI | Publish and find services | OASIS (committee finished 2007, per Wikipedia) | Registry nobody kept up to date |
| WS-Security | Signing and encrypting parts of a message, tokens | OASIS Standard 1.1.1, 18 May 2012 | XML signature canonicalisation, big headers |
| WS-ReliableMessaging | Reliable delivery between endpoints across failures | OASIS Standard 1.2, 2 February 2009 | Sequences, acknowledgements, state on both ends |
| WS-Addressing, WS-Policy, WS-Transaction, WS-Coordination | Routing headers, policy, distributed transactions | W3C / OASIS (not read by us) | Each adds headers and a coordinator |
| BPEL, WS-CDL | Orchestration and choreography languages | OASIS, 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=51Remember 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| Aspect | Canonical model | Per-pair translation | Bounded contexts (DDD) |
|---|---|---|---|
| Translators needed | 2N | N×(N−1) | One per relationship, in an ACL |
| Change to a field | Committee, all users | Two parties | The owning context only |
| Meaning of "Customer" | One, compromised | Whatever each pair agrees | One per context |
| Failure mode | Lowest common denominator, years of meetings | Spaghetti | Duplicated concept, explicit translation |
| Where it fits | Stable domains (payments messages, healthcare HL7, ISO 20022) | A handful of systems | Most 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".
| Myth | What actually happened | What to do instead |
|---|---|---|
| "Build reusable services, assemble apps later" | Services built for nobody; consumers needed different fields | Build for the first consumer, generalise at the third |
| "A central board keeps the architecture clean" | Weeks per approval, workarounds in secret | Guardrails (linters, templates), review by exception |
| "A registry makes services discoverable" | UDDI not adopted; the registry rotted | Developer portal owned by the provider team |
| "The ESB gives loose coupling" | Every flow depended on the bus team | Smart endpoints, dumb pipes |
| "Wrap the monolith and you have SOA" | Same release train, new latency | Extract along business capabilities |
| "One canonical model reduces cost" | The model became the most-changed asset | Per-context models plus explicit translation |
| "Orchestration engine = business agility" | Business logic hidden in XML flows | Keep 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
Must-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."
| Dimension | SOA (orchestration-driven, 2000s) | Microservices | Service-based architecture |
|---|---|---|---|
| Primary goal | Enterprise-wide reuse and integration | Independent change and deploy | Pragmatic domain split |
| Service size | Business services very coarse, enterprise services very fine | Fine, one bounded context | Coarse (about 4 to 12 domain services) |
| Data | Shared databases behind wrappers, canonical model | Database per service | Often one shared database |
| Pipe | Smart: ESB with routing, transformation, rules | Dumb: HTTP or broker | Direct calls from UI; little middleware |
| Flow control | Central orchestrator (BPEL, BPMN) | Choreography with events, local sagas | Within a service, local transactions |
| Governance | Central board, enterprise standards | Decentralised, team standards | Light, architect-led |
| Deployment | Services in application servers, often released together | Independent pipelines and containers | A few independent deployments |
| Protocols | SOAP, WSDL, WS-*, JMS, MQ | REST/JSON, gRPC, Kafka, AMQP | REST or RPC from the UI |
| Contract style | Canonical XML schemas | Per-service API, consumer-driven contracts | Shared or per-service |
| Failure handling | Reliable messaging, XA / compensation in the engine | Timeouts, retries, circuit breakers, sagas | Database transactions |
| Typical team | Central integration team plus app teams | Product team owns a service end to end | Domain teams, shared platform |
| Where it hurts | Bus bottleneck, committees, XML mapping | Operations, distributed data, observability | Shared 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.
| Property | Service-based architecture (Richards & Ford, paraphrase) |
|---|---|
| Number of services | Typically 4 to 12 coarse "domain services" |
| Database | Usually one shared database (can be split per domain with care) |
| Integration | UI or API layer calls services directly; no orchestration engine |
| Deployment | Each domain service deployed independently; far fewer pipelines than microservices |
| Strengths | Cheap, understandable, testable, good agility and fault isolation for the cost |
| Weaknesses | Coarse services still share a schema; scalability and elasticity limited compared with microservices |
| Good fit | Medium 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 idea | Where it lives now | Example |
|---|---|---|
| Contract-first design | OpenAPI, protobuf, AsyncAPI, consumer-driven contract tests | contract/transfers.openapi.yaml in this chapter |
| Service registry | Service discovery, developer portals, API catalogues | Consul, Kubernetes Services, Backstage |
| ESB mediation and policy | API gateway and management: auth, quotas, versioning, analytics | Kong, Apigee, AWS API Gateway, Traefik; see gateways |
| ESB protocol bridging | iPaaS and integration frameworks | Apache Camel, Spring Integration, MuleSoft |
| Canonical model | Industry standards; schema registry for events | ISO 20022, Avro schemas in Confluent Schema Registry |
| Orchestration engine | Durable workflow engines, sagas | Temporal, Camunda, Laravel queue chains, see durable workflows |
| Enterprise integration patterns | The vocabulary of every broker-based system | Router, Translator, Splitter; see routing |
| Infrastructure services | Platform capabilities | Central IdP, audit pipeline, observability |
| Service description and policy | Gateway policies, service mesh configuration | mTLS, 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."
| Concern | Rule for SOAP integration | Where in our code |
|---|---|---|
| Boundary | One adapter implements the domain port | acl/adapter.go, LegacyTransferAdapter.php |
| Money | Integer minor units inside; decimal string only at the edge | decimal() in both adapters |
| Errors | Map legacy codes to domain errors once | translate() |
| Faults | SOAP 1.1 faults arrive as HTTP 500 with a body: parse first | soapclient/client.go |
| Timeouts | Always set connect and total timeouts | connection_timeout, Http::timeout() |
| Retries | Only when the provider de-duplicates on a reference | Reference field = idempotency key |
| WSDL | Cache it; do not fetch per request | WSDL_CACHE_DISK |
| Contract drift | Keep a recorded fixture and a contract test | client_test.go round-trip |
| Strangler | Route new traffic to a new service, shrink the adapter | strangler 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
// 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
// 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
// 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:
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:
// 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
| Topic | Go approach | Note |
|---|---|---|
| XML | encoding/xml structs with namespace tags | Unmarshal ignores unknown elements by default: tolerant reader |
| HTTP client | net/http with http.Client{Timeout} and context | Always set a timeout; the default client has none |
| Routing | http.ServeMux with method patterns (POST /v1/transfers) | No router library needed |
| Contract-first | Generate server stubs from OpenAPI (oapi-codegen) or write by hand | Keep the YAML in the repo |
| SOAP libraries | Third-party (gosoap, hooklift/gowsdl) | Read the generated code before trusting it |
| Testing | httptest.NewServer and recorded envelopes | One 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
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:
<?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
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
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
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
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
| Topic | Laravel 13 / PHP 8.4 approach | Note |
|---|---|---|
| SOAP client | SoapClient (ext-soap), SOAP_1_1, exceptions => true, connection_timeout, cache_wsdl | Catch SoapFault; wrap in domain exceptions |
| SOAP over HTTP | Http::withBody(), withHeaders(), timeout(), retry() | Fake in tests with Http::fake() |
| SOAP server | Not built in; use SoapServer or a package, or avoid it | Do not add SOAP to a new system |
| Port binding | $this->app->bind(TransferPort::class, ...) in a provider | Swap adapter for a native service later |
| Validation | $request->validate([...]) with dotted keys | Matches the OpenAPI schema |
| Idempotency | Cache::get/Cache::put keyed by header, or a database unique key | Use the database for money |
| Orchestration | A service class or Bus::chain() plus a process table | See worked example |
| Choreography | Events and queued listeners, ideally with a broker | See 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
// 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
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:
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 closedMicroservice style: choreography
// 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
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 customerTrade-offs
| Question | Orchestrated (SOA) | Choreographed (microservices) |
|---|---|---|
| Where is the business flow written? | One class and one table | Spread over four listeners |
| Adding "AML check after fraud" | Edit the orchestrator, redeploy it | New service subscribes to TransferApproved, publishes its own event; fraud and accounts must agree on ordering |
| Debugging a stuck transfer | SELECT from transfer_process | Correlate events across services with a trace id |
| Failure of the orchestrator | Transfers pause; recovery job resumes | No central part to fail; each service retries its inbox |
| Coupling | Orchestrator knows every service's API | Services know event schemas |
| Ownership | Platform or integration team owns the flow | Each team owns its reaction |
| Delivery guarantee needed | Reliable call plus persisted state | At-least-once events, idempotent consumers, outbox |
| Good fit | Few steps, strong audit, regulated flow | Many 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
| Part | SOAP 1.1 | REST/JSON |
|---|---|---|
| Operation name | SOAPAction header and body element | HTTP method plus URL |
| Payload | Body with a typed element | JSON document |
| Metadata | Header blocks (security, addressing, correlation) | HTTP headers |
| Error | Fault with faultcode, faultstring, detail (HTTP 500) | HTTP status plus problem+json |
| Typing | XSD | JSON Schema in OpenAPI |
| Service description | WSDL (types, message, portType, binding, service) | OpenAPI document |
| Caching | None (POST) | GET with ETag, Cache-Control |
| Retry safety | Provider-defined; use a reference field | Idempotency-Key, PUT |
Error codes and what to do
| Where | Signal | Meaning | Retry? |
|---|---|---|---|
| SOAP | faultcode Client (1.1) | Your message is wrong | No |
| SOAP | faultcode Server (1.1) | Provider failed | Maybe, if idempotent |
| SOAP | detail/ErrorCode 51 | Insufficient funds (our example) | No |
| SOAP | detail/ErrorCode 91 | Authoriser unavailable | Yes, same reference |
| HTTP | 503 plus Retry-After | Overloaded or maintenance | Yes, same key |
| HTTP | Timeout, connection reset | Unknown outcome | Yes, only with idempotency |
| REST facade | 422 problem+json | Business rejection | No |
| REST facade | 200 on replay | Same key seen before | Not needed |
Solving the classic problems
| Problem | Solution | How | Cost |
|---|---|---|---|
| ESB as a bottleneck | Move logic to services, keep a thin gateway | Gateway: auth, quotas, routing only | Services must own validation |
| Canonical model deadlock | Per-context models plus anti-corruption layers | Translate at each boundary | More mapping code, explicit |
| No distributed transaction | Saga with compensation | Orchestrator or events; saga | Eventual consistency, UX for pending states |
| Duplicate calls after timeout | Idempotency key as legacy reference | One id for the whole chain | Key storage, expiry policy |
| Legacy SOAP spreads | Anti-corruption layer | Domain port, one adapter | One more layer to test |
| Contract drift | Contract tests, recorded envelopes | Replay fixtures in CI | Maintenance of fixtures |
| Shared reusable service blocks teams | Copy-then-extract, or consumer-driven contracts | Let teams own a slice | Some duplication |
| Orchestrator crash | Persist state, recovery job | transfer_process table | A process table to operate |
| Message loss between services | Outbox plus at-least-once, idempotent consumer | Outbox | Delay, duplicates handled |
| Slow SOAP provider | Timeout, circuit breaker, bulkhead | context timeouts, breaker library | Degraded features |
Choosing
| Situation | Recommendation | Technique | Why |
|---|---|---|---|
| New product, one team | Modular monolith | Internal ports | Cheapest; see modular monolith |
| 10 to 50 engineers, clear domains | Service-based architecture | 4 to 12 domain services | Independent deploys without microservice cost |
| Many teams, independent scaling needs | Microservices | Dumb pipes, event contracts | Team autonomy; see microservices |
| Must consume a bank's SOAP API | Anti-corruption layer | Port plus adapter | Keeps legacy out of the domain |
| Integrating 20 existing packaged systems | Integration platform or ESB-like product | Camel, MuleSoft, iPaaS; logic stays in systems | Legitimate ESB use: connect, do not decide |
| Regulated multi-step flow | Orchestrated workflow with audit | Temporal, Camunda, or a process table | One place to prove what happened |
| Many reactions to an event | Choreography | Broker and idempotent consumers | Teams add reactions without a release |
| Public API for partners | REST/JSON with OpenAPI | Gateway, quotas, versioning | Reach 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
| Load | Design | Notes |
|---|---|---|
| 1x: 10 transfers per minute | Monolith, one TransferPort, SOAP adapter inside | Timeouts and idempotency from day one |
| 10x: 100 per minute | Queue the SOAP calls, workers with limited concurrency | The legacy system's capacity is the ceiling; respect it |
| 100x: 1,000 per minute | Extract payments service, outbox, saga, rate-limited ACL | Gateway quotas protect the legacy provider |
| 1,000x and many teams | Per-domain services, events, schema registry, workflow engine for regulated flows | Retire 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.
- Run the tests that already contain the fake legacy provider:
cd docs/snippets/architecture/service-oriented-architecture/go
go test ./... -v
# expected: soapclient TestSuccess and TestFaultOnHTTP500 pass; acl TestFaultMapping passes- Break the contract on purpose: in
soapclient/client_test.gorename thefromAccountelement in the fixture and run again. Expected: the server-side assertion fails, which is how contract drift is caught. - Change the fault code from
51to91: expected resultErrUnavailable. Write a test proving the REST handler answers 503 withRetry-After. - Send the same
POST /v1/transferstwice with oneIdempotency-Key: expected 201 then 200, and the fake port counts one call (seerestapi/handler_test.go). - Run the orchestrator test (
orchestrator_test.go): credit fails, state endsCOMPENSATED, last call isrefund. - 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
CustomerNotifiednever appears?
Common misconceptions
| Belief | Reality |
|---|---|
| SOA is SOAP | OASIS defines SOA as a paradigm; SOAP was one common implementation |
| An ESB is a message broker | A broker moves messages; an ESB also mediates, transforms and orchestrates |
| Microservices are small SOA services | The differences are data ownership, pipe intelligence and governance, not size |
| Reuse justifies every service | Reuse is found after the third consumer, not designed up front |
| A canonical model reduces coupling | It couples every system to one schema owned by a committee |
| WSDL generated from code is contract-first | Contract-first means the contract is written before the code |
| Wrapping a monolith in services gives agility | The release cycle stays tied to the monolith |
| SOAP is dead | Banks, governments, ERP and telecom still publish SOAP; you must integrate cleanly |
| Choreography is always better than orchestration | Regulated flows often want one place that can prove what happened |
| UDDI is how discovery works today | It was not widely adopted; catalogues and discovery systems replaced it |
Cheat sheet
| Topic | What to remember |
|---|---|
| Definition | OASIS: a paradigm for organising distributed capabilities under different ownership domains |
| Core idea | Services with published contracts and loose coupling |
| Eight principles | Contract, loose coupling, abstraction, reusability, autonomy, statelessness, discoverability, composability |
| Four service types | Business, enterprise, application, infrastructure |
| ESB | Mediation, routing, transformation, orchestration; smart pipe |
| Orchestration vs choreography | Central conductor vs reacting dancers |
| WS-* | SOAP, WSDL, UDDI, WS-Security, WS-ReliableMessaging; heavy |
| SOAP 1.1 fault | Arrives as HTTP 500 with a Fault body |
| Canonical model | Cheap at 6 systems (12 vs 30 translators), expensive to govern |
| Governance | Central boards slowed change; use guardrails |
| Microservices | Smart endpoints, dumb pipes, database per service |
| Service-based | 4 to 12 coarse services, often shared database |
| Legacy SOAP | Wrap in an anti-corruption layer; integer money inside |
| Idempotency | One id from edge to legacy reference |
| What survives | Contract-first, API management, EIP, workflow engines |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| SOA | Service-Oriented Architecture: organising capabilities as services with published contracts |
| Service | Mechanism to access a capability through a prescribed interface (OASIS) |
| Service contract | Machine-readable description of operations, messages and policy |
| SOAP | XML messaging framework with envelope, header, body, fault |
| WSDL | XML description of operations, messages, bindings and addresses |
| XSD | XML Schema Definition, the type system of SOAP messages |
| UDDI | Registry specification for publishing and finding services |
| WS-Security | OASIS spec for signing and encrypting SOAP messages |
| WS-ReliableMessaging | OASIS spec for reliable delivery between SOAP endpoints |
| WS-* | Family of specifications stacked on SOAP |
| ESB | Enterprise Service Bus: central mediation, routing, transformation layer |
| Mediation | Intermediary between consumer and provider |
| Orchestration | Central process that calls services in order |
| Choreography | Services coordinating through events, no central owner |
| BPEL | XML language for orchestrating web services |
| Canonical data model | Shared enterprise message vocabulary |
| Anti-corruption layer | Adapter that translates a foreign model into the domain's |
| Service-based architecture | Few coarse domain services, often a shared database |
| Smart pipes | Middleware holding routing and business logic |
| Dumb pipes | Transport that only moves messages |
| Contract-first | Write the contract before the implementation |
| Idempotency key | Id making a repeated request produce the same result |
| Compensation | Action that semantically undoes an earlier step |
| Strangler fig | Gradual replacement of a legacy system behind a facade |
| API management | Gateway, quotas, portal and versioning for APIs |
References
- OASIS, Reference Model for Service Oriented Architecture 1.0, 12 October 2006: https://docs.oasis-open.org/soa-rm/v1.0/soa-rm.html
- W3C, SOAP Version 1.2 Part 1: Messaging Framework (Second Edition), 27 April 2007: https://www.w3.org/TR/soap12-part1/
- W3C, Web Services Description Language (WSDL) 1.1, Note, 15 March 2001: https://www.w3.org/TR/2001/NOTE-wsdl-20010315
- W3C, WSDL Version 2.0 Part 1: Core Language, 26 June 2007: https://www.w3.org/TR/wsdl20/
- OASIS, Web Services Security: SOAP Message Security 1.1.1, 18 May 2012: https://docs.oasis-open.org/wss-m/wss/v1.1.1/os/wss-SOAPMessageSecurity-v1.1.1-os.html
- OASIS, WS-ReliableMessaging 1.2, 2 February 2009: https://docs.oasis-open.org/ws-rx/wsrm/v1.2/wsrm.html
- Fowler and Lewis, Microservices (smart endpoints and dumb pipes; Microservices and SOA): https://martinfowler.com/articles/microservices.html
- Fowler, Service Oriented Ambiguity, 1 July 2005: https://martinfowler.com/bliki/ServiceOrientedAmbiguity.html
- Thoughtworks Technology Radar, Overambitious API gateways: https://www.thoughtworks.com/radar/platforms/overambitious-api-gateways
- Hohpe and Woolf, Canonical Data Model (Enterprise Integration Patterns): https://www.enterpriseintegrationpatterns.com/patterns/messaging/CanonicalDataModel.html
- Microsoft Learn, Anti-corruption layer pattern: https://learn.microsoft.com/en-us/azure/architecture/patterns/anti-corruption-layer
- PHP manual, The SoapClient class: https://www.php.net/manual/en/class.soapclient.php
- Laravel 13 documentation, HTTP Client: https://laravel.com/docs/13.x/http-client
- Go documentation, package
encoding/xml: https://pkg.go.dev/encoding/xml - Wikipedia, Service-oriented architecture and Universal Description Discovery and Integration (secondary, used for the principle names and UDDI history): https://en.wikipedia.org/wiki/Service-oriented_architecture
- Richards and Ford, Fundamentals of Software Architecture (O'Reilly, 2020): orchestration-driven service-oriented architecture and service-based architecture chapters. Not fetched online; paraphrased with no quotations.
- Newman, Building Microservices, 2nd ed. (O'Reilly, 2021): background on the SOA history. Not fetched online; used for orientation only.