1. Understand the Goal: The user wants a "backend playbook" that helps engineers/developers decide whether to implement a specific feature or piece of logic as a Domain Service, an Event Handler, or a Trigger (e.g., Database Trigger, Cron Job, or Infrastructure-level trigger). The output should be a structured guide/playbook.
-
Target Audience: Backend developers, software architects, and tech leads. The tone should be professional, technical, and decision-oriented.
-
Key Concepts:
- Domain Service: Logic that doesn't naturally fit within a single Entity or Value Object. Often involves orchestrating multiple aggregates or external dependencies. Key: Synchronous, immediate consistency (usually), core business logic.
- Event Handler: Reactive logic. "When X happens, do Y." Decoupled. Often asynchronous (eventual consistency). Good for side effects, notifications, and syncing to read models.
- Trigger:
- Database Trigger: Low-level, automatic data integrity or audit logging. Hard to debug, tightly coupled to schema.
- Infrastructure/System Trigger (e.g., Cron, Webhooks): Time-based or external system initiated.
- Note: I need to clarify what "Trigger" means in this context. Usually, in a DDD/Backend context, it might mean DB triggers or "System Triggers" (like a CRON job or a specific API endpoint acting as a trigger). Given the comparison with Domain Services and Event Handlers, "Database Trigger" is a specific architectural choice, but "Time-based/System Trigger" is also valid. I will assume "Database Trigger" as the primary comparison point for implementation logic, but mention Cron/System triggers as an alternative for "background tasks." Self-correction: Usually, when people ask this specific triad, they are talking about where the business logic lives:
- Service method (Direct call).
- Event Subscriber (Reactive).
- DB Trigger (Implicit/Data-bound).
Decision: I will focus on DB triggers for the "Trigger" section but acknowledge "Scheduled/Infrastructure Triggers" briefly as a separate category to avoid confusion.
-
Structure of the Playbook:
- Title: Clear and professional.
- Executive Summary: Quick overview.
- Definitions (The "What"): Briefly define the three contenders.
- Decision Matrix (The "How"): The core logic.
- Playbook Sections (Deep Dives):
- When to use Domain Services.
- When to use Event Handlers.
- When to use Triggers.
- Code/Scenario Examples: Concrete scenarios.
- Antipatterns/Red Flags: Warning signs.
- Summary Flowchart (Text-based): A quick heuristic.
-
Drafting Content - Section by Section:
-
Definitions:
- Domain Service: Stateless, verb-heavy, orchestrates business rules.
- Event Handler: Reactive, eventually consistent, side effects.
- Trigger: Implicit, database-level, strict data integrity (auditing, derived columns).
-
Decision Criteria:
- Visibility: Do I see the code execution? (Service > Handler > Trigger).
- Consistency: Do I need it now? (Service/Trigger vs Handler).
- Coupling: Is this logic core to the entity or an add-on?
-
Domain Service:
- Use when: Logic spans aggregates, needs transaction, calculation heavy, "noun + verb".
- Example:
TransferMoney(sourceAcc, destAcc, amount).
-
Event Handler:
- Use when: Decoupling, side effects, notifications, 3rd party API calls that might fail, eventual consistency is okay.
- Example: Send email "Welcome" after UserCreated.
-
Triggers (DB):
- Use when: Very sparingly. Audit logs that must never be bypassed, complex data integrity constraints (circular checks) that code might miss.
- Warning: Testing hell, debugging nightmare.
-
Refining the "Trigger" Concept:
If the user meant "Cloud Function/Lambda Trigger" or "Cron Job," the playbook changes. However, "Domain Service vs Event Handler vs Trigger" is a classic architectural debate usually centering on business logic placement.
- Interpretation A: DB Triggers. (Most likely in a strict data modeling context).
- Interpretation B: System Triggers (Cron/Scheduled).
- Interpretation C: Application-level "Trigger" (like a Factory or Strategy pattern? Unlikely).
Decision: I will treat "Trigger" primarily as Database Triggers but add a sidebar/section for System/Scheduled Triggers to ensure comprehensive coverage.
-
Developing the Evaluation Flow (The "Playbook" aspect):
I need a set of questions the developer asks themselves.
- Q1: Does this involve multiple aggregates? -> Domain Service.
- Q2: Is it a side effect of an action? -> Event Handler.
- Q3: Is it strictly data integrity enforcement? -> Trigger.
-
Formatting: Use Markdown with bolding, lists, and clear headers to make it readable as a "playbook."
-
Self-Correction during drafting:
- Initial thought: Just list pros/cons.
- Correction: A playbook needs actionable steps. I should frame it as "If [condition], then choose [Option]."
- Emphasis: Emphasize testing. Triggers are hard to test; Domain services are easy. This is a major factor.
-
Final Polish: Ensure consistent terminology (DDD terms like Aggregate, Entity, Bounded Context). Add a disclaimer that "Trigger" usually implies DB triggers, but clarify if needed.
(Self-Correction on "Trigger" definitions again): Some frameworks (like Firebase or serverless) use "Triggers" to mean "Event Handlers." Since the prompt lists "Event Handlers" separately, "Triggers" almost certainly refers to Database Triggers (SQL CREATE TRIGGER). I will proceed with this assumption but add a note about Cron/Scheduled tasks just in case.
-
Constructing the Output: (This aligns with the generated response structure).
- Introduction.
- The Decision Framework (The "Cheat Sheet").
- Deep Dive: Domain Services.
- Deep Dive: Event Handlers.
- Deep Dive: Triggers (Database).
- Comparative Analysis (Testing, Debugging, Performance).
- Scenario Examples.
-
Review against constraints: "Backend playbook." "Evaluating implementation." "Domain Services, Event Handlers, Triggers." All met.
(Final thought during drafting content): Make sure to distinguish between Domain Events (in-process) and Integration Events (out-of-process). The playbook applies to both, but the "Trigger" comparison is most relevant when talking about implicit behavior vs explicit code.
Let's write it.
Backend Implementation Playbook: Services vs. Handlers vs. Triggers
Objective: To provide a decision framework for backend engineers and architects when implementing business logic.
Goal: Maximize maintainability, testability, and system observability while minimizing coupling and technical debt.
1. The Decision Matrix (TL;DR)
| Implementation Type | Use When... | Key Characteristic |
|---|
| Domain Service | The logic is the primary goal of the user's request. It requires immediate feedback (validation) and transactional consistency. | Synchronous / Orchestrator |
| Event Handler | The logic is a side effect of the primary goal. It can happen eventually, and failure should not roll back the primary transaction. | Asynchronous / Reactive |
| Trigger | The logic is a data integrity constraint or audit requirement that must apply regardless of how the data was modified (API, SQL, Admin). | Implicit / Database-Locked |
2. Deep Dive: Domain Services
Definition: A stateless service that orchestrates business logic which does not naturally belong to a single Entity (e.g., interaction between User and Wallet).
The Protocol
Implement as a Domain Service if you answer YES to any of the following:
- Atomicity: Does this logic require a database transaction (ACID) involving multiple aggregates?
- Feedback: Does the user/client need to know the result (success/failure/error message) immediately to proceed?
- Validation: Does this logic require "heavy" validation (checking external APIs, complex business rules) before saving?
Best Practices
- Naming: Verb-centric (e.g.,
TransferFundsService, RegisterUserCommand).
- Location: Application Layer (Command Handlers) or Domain Layer.
- Testing: Must be unit testable with mocked repositories.
❌ The Anti-Pattern
Do not put logic like "Send Welcome Email" inside the Domain Service. If the email server is down, the database transaction will roll back, preventing the user from registering. Move that to an Event Handler.
3. Deep Dive: Event Handlers
Definition: A listener that reacts to an event that has already occurred (e.g., UserCreated, OrderShipped).
The Protocol
Implement as an Event Handler if you answer YES to the following:
- Decoupling: If this logic fails, should the primary action still stand? (e.g., If "Update Slack" fails, should the "Ticket" still be created? Yes.)
- Latency Tolerance: Is it acceptable for this logic to happen milliseconds or seconds later?
- Fan-out: Does one action trigger multiple disparate systems (e.g., User Signup -> Email, Analytics, CRM)?
Types of Handlers
- In-Process (Sync): Runs immediately after the transaction commits. Good for cache invalidation.
- Out-of-Process (Async/Queued): Pushes to RabbitMQ/Kafka. Good for external APIs, emails, and heavy processing.
❌ The Anti-Pattern
Do not put business validation in an Event Handler. You cannot stop the event from happening if the handler fails validation. Validation belongs in the Domain Service before the event is emitted.
4. Deep Dive: Triggers (Database)
Definition: Procedural code automatically executed in response to certain events on a particular table or view (e.g., PL/SQL, T-SQL).
The Protocol
Implement as a Database Trigger ONLY if you answer YES to the following:
- Invisibility: Must this logic run even if a DBA manually updates a row via SQL?
- Data Integrity: Is this logic strictly about preventing invalid data states (e.g., preventing a negative balance no matter what)?
- Audit: Is this strictly for audit logging columns (
updated_at, created_by) that are tedious to manage in application code?
The Rules of Engagement
- Keep them STUPID: Triggers should contain very little logic. They should be simple constraints or value updates.
- No External Calls: Triggers should never call external APIs or services. They run inside the database transaction space.
- Documentation: Triggers are "magic." They must be documented in the schema migration files and the internal developer wiki.
❌ The Anti-Pattern
Never use triggers to implement core business logic (e.g., calculating complex commissions). Triggers are notoriously hard to debug, version control, and test. They hide logic from the application code.
5. Scenario Evaluation
Let's apply this playbook to common scenarios.
Scenario A: "When a user registers, check if they are over 18 and save their profile."
- Decision: Domain Service.
- Reason: You must verify age before saving. If they are underage, you must abort the transaction immediately and return an error to the UI.
Scenario B: "When a user registers, send them a confirmation email."
- Decision: Event Handler (Async).
- Reason: The user is valid. The email is a side effect. If the email provider is down, the user should still exist in the DB. You can retry the email later.
Scenario C: "When an order is placed, update the last_order_at timestamp on the customer record."
- Decision: Domain Service (Preferred) OR Event Handler.
- Reason: It's a data update. A Domain Service can update both the Order and Customer in one transaction. An Event Handler is acceptable here if eventual consistency is allowed.
Scenario D: "Ensure the inventory_count never drops below zero."
- Decision: Domain Service (Check logic) + Database Constraint (Fail-safe).
- Reason: The Service should handle the logic. However, for critical financial/inventory data, a Trigger or Constraint acts as a "seatbelt" to prevent race conditions or buggy code from corrupting data.
Scenario E: "Automatically populate updated_at timestamp on every row change."
- Decision: Trigger.
- Reason: This is a cross-cutting infrastructure concern. It applies to every update, regardless of context, and is tedious to write in code for every entity.
6. Summary Flowchart
-
Is it validation?
- Yes -> Domain Service (Fail fast).
- No -> Go to 2.
-
Does it require atomicity (must happen together or not at all)?
- Yes -> Domain Service (Transaction scope).
- No -> Go to 3.
-
Is it a side effect (notifications, analytics, search indexing)?
- Yes -> Event Handler (Decouple and scale).
- No -> Go to 4.
-
Is it data auditing or a hard constraint that must apply even to manual SQL edits?
- Yes -> Trigger (Use sparingly).
- No -> Domain Service (Default location for logic).
7. Operational Checks
Before merging code, the reviewer should ask: