Junior — Middle
How were updates performed in the shared database for individual microservices?
sobes.tech AI
Answer from AI
In a microservices architecture, sharing a single database among multiple services is usually avoided to prevent tight coupling. However, if a shared database is used, updates for each microservice are performed using transactions that ensure data integrity.
Common approaches include:
- Database-level transactions — each microservice performs its operations within a transaction to ensure atomicity.
- Optimistic locking — to prevent conflicts during concurrent updates.
- Event Sourcing and CQRS — updates occur through events that are applied to the database, allowing synchronization of state.
Example in Java using Spring and JPA:
@Transactional
public void updateEntity(EntityDto dto) {
Entity entity = repository.findById(dto.getId())
.orElseThrow(() -> new EntityNotFoundException());
entity.setField(dto.getField());
repository.save(entity);
}
Here, the @Transactional annotation guarantees that the update is performed atomically.