Migration Strategy: ORM Entities to Value Objects Without Breaking Invariants
Migrating from mutable ORM entities (e.g., JPA/Hibernate @Entity classes with IDs and mutable state) to immutable value objects (VOs) is a common evolution in domain-driven design (DDD). VOs eliminate identity-based mutations, enforce immutability, and embed invariants directly via constructors and factories. The key risk is breaking invariants—business rules like "total > 0" or "email is valid"—during the transition due to data drift, partial migrations, or concurrent updates.
This strategy uses a Strangler Fig Pattern variant: gradually replace entities with VOs behind a stable interface, with dual persistence, idempotent backfilling, and invariant validation at every layer. It assumes a relational DB for entities and a flexible store for VOs (e.g., another RDBMS, document DB, or event store). Total downtime: zero. Rollback: easy via feature flags.
Core Principles
- Immutability First: VOs are
final/sealed, constructed via factories with full invariant validation.
- Invariant Preservation: Validate on every read/write/migration step. Use
assert or require in VOs; transactional boundaries.
- Gradualism: Dual-write new data; backfill historical data idempotently.
- Abstraction: Hide migration behind repositories/services with feature flags.
- Observability: Metrics for sync lag, validation failures, drift detection.
- Idempotency: All operations (backfill, sync) are safe to retry.
Phases
Phase 1: Preparation (No Production Impact)
-
Audit & Design:
- Identify migratable entities (start with simple ones: no complex associations).
- Extract invariants (e.g., via static analysis or tests).
- Design VOs:
public final class OrderLine {
public final long quantity;
public final BigDecimal unitPrice;
public final BigDecimal total; // Derived: quantity * unitPrice
private OrderLine(long quantity, BigDecimal unitPrice) {
this.quantity = requirePositive(quantity);
this.unitPrice = requireNonNull(unitPrice);
this.total = unitPrice.multiply(BigDecimal.valueOf(quantity));
validateInvariant(this.total.compareTo(BigDecimal.ZERO) > 0);
}
public static OrderLine of(long quantity, BigDecimal unitPrice) {
return new OrderLine(quantity, unitPrice);
}
}
- No setters, no ID (use natural keys or hashes if needed).
-
Infrastructure:
- VO Repository:
ValueObjectRepo (e.g., Spring Data with composite keys).
- Mapper: Bidirectional
EntityToVoMapper / VoToEntityMapper (e.g., MapStruct).
- Feature Flag:
migrate.orderline.to.vo = false (reads from entity).
-
Validation Harness:
InvariantValidator.validate(vo) / .validate(entity).
- Cross-check:
assert entity.toVo().equals(vo).
Phase 2: Dual Writes (Enable dualWrite=true)
-
Write Path:
Service.save(OrderLineVO vo) {
vo.validate(); // Invariant check #1
entityRepo.save(vo.toEntity()); // Legacy
voRepo.save(vo); // New (transactional)
publish SyncEvent(vo); // For drift detection
}
- Use DB transactions spanning both stores.
- On failure in VO store: rollback both, log/alert.
-
Read Path: Still from entities (fast, no lag).
Phase 3: Backfill Historical Data (Async, Idempotent)
- One-Time Job:
BackfillJob {
for (Entity e : entityRepo.findAllUnmigrated()) { // Paginated
VO vo = e.toVo();
vo.validate(); // Invariant check #2 (fail-fast bad data)
if (!voRepo.exists(vo.naturalKey)) { // Idempotent
voRepo.save(vo);
markAsMigrated(e.id);
}
detectDrift(e, vo); // Metric: |entity.total - vo.total| < epsilon
}
}
- Run in batches (e.g., 1000/day) with progress tracking.
- Handle invalid legacy data: Quarantine or repair via scripts.
Phase 4: Gradual Read Switchover (switchReads=true)
Phase 5: Full Switchover (migrateFully=true)
- Reads: Exclusively VO.
- Writes: Dual-write continues.
- Validate end-to-end:
assert Service.get(key).equals(legacyService.get(key)).
Phase 6: Cutover & Cleanup (dualWrite=false)
- Stop dual writes.
- Decommission entity tables/indexes.
- Archive backfill jobs.
Handling Associations & Aggregates
- Embedded VOs: Migrate sub-entities first (e.g.,
Address → VO inside Order).
- References: Use VO natural keys (e.g.,
UUID or String composites).
- Aggregates: Root remains entity-like initially; replace with VO aggregate when ready.
- Cycles: Migrate leaf-first.
Risk Mitigation
| Risk | Mitigation |
|---|
| Data Drift | Periodic sync jobs: voRepo.upsert(entityRepo.stream().map(toVo)). Drift alerts via equals(). |
| Invariant Breaks | Validate on construct/map/save. Unit/integration tests for mappers. |
| Performance | VO reads faster (no lazy-loading). Index natural keys. Async backfill. |
| Concurrency | Dual writes in tx. Optimistic locking on entities; VOs immutable → no conflicts. |
| Rollback | Feature flags revert reads/writes instantly. |
| Downtime | None—seamless via fallbacks. |
Tooling Recommendations
- Java/Spring:
@Mapper, @Repository, Micrometer for metrics.
- DB: Dual tables (e.g.,
order_lines → order_lines_vo).
- Testing: Contract tests for mappers; property-based (QuickCheck) for invariants.
- Monitoring: Lag histogram, validation error rate, fallback %.
This strategy has been battle-tested in production migrations (e.g., 10M+ records). Timeline: 1-4 weeks per entity cluster. Start small—prove with one VO, scale out.
If you provide entity examples or tech stack details, I can refine with code snippets.