Tell me about the in-memory storage of positions and balances with synchronous persistence from the resume.
sobes.tech AI
Answer from AI
In-memory storage of positions and balances is a data structure that keeps current values of positions and balances in RAM for quick access and updates. Synchronous persistence means that every change is simultaneously written to a long-term storage (such as a database or file) to prevent data loss in case of failure.
In the context of Golang, such a system might look like a map with a mutex for thread safety, where the key is the position or account identifier, and the value is a structure with the balance. When updating the balance, the in-memory structure is first updated, then a synchronous write to the database is performed. This ensures data consistency between memory and disk.
An example of a simplified implementation:
type BalanceStore struct {
mu sync.Mutex
balances map[string]float64
db *sql.DB
}
func (bs *BalanceStore) UpdateBalance(id string, amount float64) error {
bs.mu.Lock()
defer bs.mu.Unlock()
bs.balances[id] += amount
// Synchronous write to DB
_, err := bs.db.Exec("UPDATE balances SET amount = ? WHERE id = ?", bs.balances[id], id)
if err != nil {
// Rollback in case of error
bs.balances[id] -= amount
return err
}
return nil
}
This approach allows fast reading and updating of data in memory, while ensuring that data is not lost in case of failure, as the write to the database is performed synchronously.