Managing associations through an aggregate root

You would need to do such a lock anyways, since as it is written now you could end up in the same situation. create_topic could be called from multiple processes as it is!

But .. this is what databases are for: ACID. I would personally put such a constraint check in the database itself, either as a constraint on the relevant fields, or as a function used as a constraint trigger. Putting constraints that require global consistency in the application layer is rarely worth it. This would also obviate the need to fetch the current topics (with a lock, no less): the topic number could be set and the constraints checked in the database itself, and it would be done with guaranteed consistency. So, better guarantees and fewer roundtrips to the database. Constraint violations are returned as errors from Ecto, so you would be able to detect the violations in the application code still.