Hmm, the user wants a decision framework for choosing between domain services, event handlers, or triggers in backend architecture. This is a practical architectural question that needs clear, actionable criteria rather than theoretical definitions.
I should structure this as a playbook with a hierarchical decision flow. Start with a high-level overview to set context, then dive into concrete evaluation questions for each pattern. The key is to make the distinctions tangible - not just "what they are" but "when to pick which."
For domain services, emphasize synchronization and complex business logic. For event handlers, highlight decoupling and eventual consistency. For triggers, focus on operational simplicity and direct database reactions. The decision matrix at the end will help users quickly reference trade-offs.
Need to avoid academic language and keep it engineer-friendly. Use concrete examples (e.g., "sending confirmation emails" for handlers) to illustrate abstract concepts. The summary table should be the climax - everything leads to that quick-reference tool.
Backend Architecture Decision Playbook: Domain Services vs. Event Handlers vs. Triggers
Executive Summary
This playbook provides a structured decision framework for selecting the appropriate backend pattern—Domain Services, Event Handlers, or Database Triggers—when implementing new features. Choose based on data consistency requirements, coupling tolerance, performance needs, and operational complexity.
1. Pattern Definitions & Core Purposes
| Pattern | Primary Purpose | Execution Context | Coupling | Data Consistency |
|---|
| Domain Service | Encapsulate business logic that doesn’t naturally belong to a single entity/aggregate. | Synchronous, within application service/transaction. | Low (to persistence layer) | Strong (immediate, ACID) |
| Event Handler | React to domain events asynchronously; enable decoupled side-effects. | Asynchronous (message queue/event bus). | Very Low (publish-subscribe) | Eventual (may lag) |
| Database Trigger | Automatically enforce data integrity or audit changes at the DB level. | Synchronous, within DB transaction. | High (tightly coupled to schema) | Strong (immediate, ACID) |
2. Decision Flowchart
graph TD
A[New Feature Requirement] --> B{Is logic core business rule<br>requiring immediate consistency?};
B -- Yes --> C{Does logic span multiple aggregates<br>or require complex coordination?};
C -- Yes --> D[Domain Service];
C -- No --> E{Can logic be expressed as<br>simple constraint/derivation?};
E -- Yes --> F[Consider Domain Service method<br>on aggregate root];
E -- No --> G[Re-evaluate boundaries];
B -- No --> H{Is reaction to data change?<br>Side-effect, notification, integration?};
H -- Yes --> I{Requires low coupling<br>or integration with external systems?};
I -- Yes --> J[Event Handler];
I -- No --> K{Simple data derivation/integrity<br>with no external dependencies?};
K -- Yes --> L[Database Trigger];
K -- No --> M[Event Handler still preferred];
H -- No --> N[Reassess requirement<br>Possibly invalid pattern];
3. Evaluation Questions & Scoring
A. For Domain Services:
✅ Choose if:
- Logic involves multiple aggregates (e.g., “Transfer funds between accounts”).
- Requires external APIs/services within same transaction (e.g., payment gateway call).
- Complex validation/calculation not native to a single entity.
- Needs immediate feedback/errors to API caller.
- Part of domain model (Ubiquitous Language).
❌ Avoid if:
- Only simple CRUD operations.
- Side-effects can be asynchronous.
- Introduces unnecessary transaction scope.
B. For Event Handlers:
✅ Choose if:
- Side-effects (email, analytics, cache update) that shouldn’t block main flow.
- Integration with external systems (Slack, CRM, legacy systems).
- Fan-out to multiple subsystems (e.g., “OrderPlaced” → inventory, billing, shipping).
- Loose coupling is critical (teams own their services/events).
- Failure tolerance—handler can retry/fail without breaking main transaction.
❌ Avoid if:
- Requires immediate consistency (e.g., “seat must be reserved now”).
- Simple data derivation better suited for DB view/computed column.
- Too many handlers cause “event spam” (consider sagas for orchestration).
C. For Database Triggers:
✅ Choose if:
- Critical data integrity must be enforced regardless of application layer (e.g., soft delete cascade, audit trails).
- Legacy systems where application code cannot be modified.
- Simple, performance-critical derivations (e.g., computed columns, denormalized totals).
- Compliance/auditing (automatic change tracking).
- No business logic—pure data mechanics.
❌ Avoid if:
- Contains business rules (belongs in domain model).
- Interacts with external systems (network calls in triggers are antipattern).
- Complex logic (hard to test/debug in DB).
- Schema changes frequently (triggers become brittle).
4. Trade-off Analysis
| Concern | Domain Service | Event Handler | Trigger |
|---|
| Testability | High (unit/integration tests) | Medium (integration tests) | Low (DB-dependent) |
| Debuggability | High (stack traces) | Medium (distributed tracing) | Low (DB logs) |
| Performance | Synchronous overhead | Async (faster API response) | Fast (in-DB) but can block writes |
| Scalability | Limited by transaction | High (parallel handlers) | DB bottleneck |
| Schema Coupling | Low | Low | High (tight to tables) |
| Failure Handling | Transaction rollback | Retry/DLQ | Transaction rollback |
5. Anti-pattern Checklist
🚩 Domain Service Anti-patterns:
- “God service” with 50+ methods → split by subdomain.
- Contains only CRUD → move to repository/aggregate.
- Calls multiple repositories in one transaction → consider eventual consistency.
🚩 Event Handler Anti-patterns:
- “Event soup”—too many granular events → aggregate events (e.g.,
OrderLifecycleEvent instead of OrderCreated, OrderPaid).
- Handler performs heavy sync work → move to separate service/thread.
- No idempotency → duplicate events cause corruption.
🚩 Trigger Anti-patterns:
- Business logic in triggers → violates domain-driven design.
- Triggers calling web services → can time out and break DB transactions.
- Overuse for analytics → use materialized views/ETL instead.
6. Hybrid Scenarios
| Scenario | Recommended Approach |
|---|
| Update derived data + send notification | Domain Service → emits event → handler updates cache/sends email |
| Enforce complex constraint + audit | Domain Service validation + trigger for audit trail |
| Real-time cache update + async analytics | Domain Service updates cache; emits event for analytics handler |
| Legacy DB with new app layer | Triggers for legacy integrity; events for new integrations |
7. Decision Matrix (Quick Reference)
| Requirement | Domain Service | Event Handler | Trigger |
|---|
| Must happen in same transaction | ✅ | ❌ | ✅ |
| Requires external API call | ✅ (sync) | ✅ (async) | ❌ |
| Loose coupling needed | ❌ | ✅ | ❌ |
| Simple derivation (sum/count) | ⚠️ (app layer) | ❌ | ✅ (computed column) |
| Audit trail | ⚠️ (manual) | ⚠️ (event sourcing) | ✅ (auto) |
| High write throughput | ⚠️ (txn overhead) | ✅ (async) | ❌ (lock contention) |
8. Implementation Checklist
Before committing to Domain Service:
Before committing to Event Handler:
Before committing to Trigger:
9. Migration Paths
-
Trigger → Event Handler:
Use case: Want to decouple auditing from DB.
Steps: Replace trigger with application event; write one-time migration for existing data.
-
Domain Service → Event Handler:
Use case: Side-effects slowing transactions.
Steps: Emit event from service; move side-effects to handler; ensure idempotency.
-
Event Handler → Domain Service:
Use case: Consistency issues from async processing.
Steps: Move logic into service transaction; keep event for async read-models only.
10. Final Recommendation Framework
| If your priority is... | Start with... | Then consider... |
|---|
| Simplicity & control | Domain Service | Event Handler for non-critical side-effects |
| Scalability & decoupling | Event Handler | Domain Service only for sync core logic |
| Legacy DB integrity | Trigger | Event Handler for new integrations |
| Regulatory compliance | Trigger + Event Handler | Domain Service for business rules |
Bottom Line:
- Domain Services = business logic with immediate consistency.
- Event Handlers = decoupled reactions, async integration.
- Triggers = last-resort data integrity, not business logic.
Default to Event Handlers for cross-cutting concerns; default to Domain Services for core domain rules; avoid Triggers unless absolutely necessary for data integrity.
Revision History:
v1.0 (2024) – Initial release based on DDD, CQRS, and event-driven patterns.
Next Review: When introducing new event bus or changing transaction strategy.