This is a problem I've faced in many languages over the years (js, go, c, f#, haskell, python, ...), but I haven't found a general approach to solving this yet. Learning about consistency models in databases made me realise all my approaches so far are failing in different ways, usually I end up with a ton of accidental race conditions.
I'm fetching data from a db, and storing it in data structures in memory on a server. There's no limit on how many parts of a single codebase may hold those elements at a time, so we might hold two contradictory copies of a single datum in memory if we're not careful. Some updates require atomic changes in the db (login attempts, for example), while others (like user display name) may be stale, or cached for a while. I don't want to call the db on each read/write, because it's way to slow and expensive.
How do you usually approach this problem? What's the pros/cons of your approach? Are there some language-agnostic best-practices in this area? Some way to be reasonably confident the code free from data races?
Tagging as ORM even though it's not strictly about OOP-RDBMS mappings, because I don't know what to call the more general thing.