How to delete relations with read model?

From the “Cascading deletes” topic of Andrea Ratto:

How to delete relations with read model? E.g. if I unsubscribe from facebook, all my facebook friends should lose me as a friend.

There a lot of options to handle this with the read model. Which one is preferred or is there another option?

Note: the Java code might not be fully correct.

Option 1 dispatch new commands in command handler:

@CommandHander
public void handle(UserUnsubscribe command) {
Collection users = userQueryRepository.getWithFriend(command.userId);
for (User user : users) {
commandBus.dispatch(new RemoveFriendCommand(user.id, command.userId));
}
User user = userRepository.load(command.userId);
user.unsubscribe();
}

Option 2 dispatch new commands in event handler:

@CommandHander
public void handle(UserUnsubscribe command) {
User user = userRepository.load(command.userId);
user.unsubscribe(); // publishes UserUnsubscribedEvent
}

@EventHandler
public void handle(UserUnsubscribedEvent event) {
Collection users = userQueryRepository.getWithFriend(event.userId);
for (User user : users) {
commandBus.dispatch(new RemoveFriendCommand(user.id, event.userId));
}
}

Option 3 only update query model:

@CommandHander
public void handle(UserUnsubscribe command) {
User user = userRepository.load(command.userId);
user.unsubscribe(); // publishes UserUnsubscribedEvent
}

@EventHandler
public void handle(UserUnsubscribedEvent event) {
Collection users = userQueryRepository.getWithFriend(event.userId);
for (User user : users) {
userQueryRepository.removeFriend(user.id, event.userId);
}
}

Option 3 doesn’t even update the other user’s aggregates.

I do it like option 1, but not for a specific reason… I’m curious to know what’s “the right” way as well and which can be more or applied in general.

The only right way of doing it, is the way that helps you best achieve your (non)functional requirements. If you only need to update the query model, then simply delete all relationships with that person/account.

If you track friends in the command model as well, you may have to query for all friends of the deleted account and forcibly unfriend them. In that case, both option 1 and 2 will help, where 2 I tend to favor 2 more.

Cheers,

Allard