This report documents the profiling and optimization of database operations in the next.orly.dev/pkg/database package. The optimization focused on reducing memory allocations, improving query efficiency, and ensuring proper batching is used throughout the codebase.
- SaveEvent - Event write operations
- QueryEvents - Complex event queries
- QueryForIds - ID-based queries
- FetchEventsBySerials - Batch event fetching
- GetSerialsByRange - Range queries
- GetFullIdPubkeyBySerials - Batch ID/pubkey lookups
- GetSerialById - Single ID lookups
- GetSerialsByIds - Batch ID lookups
- CPU profiling (-cpuprofile)
- Memory profiling (-memprofile)
- Allocation tracking (-benchmem)
The codebase analysis revealed several optimization opportunities:
Problem: Multiple slice allocations without capacity estimation, causing reallocations.
Solution:
results slice with estimated capacity (len(idxs) * 100)seen map with capacity of len(results)idPkTs slice with capacity of len(results)serials and filtered slices with appropriate capacitiesCode Changes (query-for-ids.go):
// Pre-allocate results slice with estimated capacity to reduce reallocations
results = make([]*store.IdPkTs, 0, len(idxs)*100) // Estimate 100 results per index
// deduplicate in case this somehow happened
seen := make(map[uint64]struct{}, len(results))
idPkTs = make([]*store.IdPkTs, 0, len(results))
// Build serial list for fetching full events
serials := make([]*types.Uint40, 0, len(idPkTs))
filtered := make([]*store.IdPkTs, 0, len(idPkTs))
Problem: Map created without capacity, causing reallocations as events are added.
Solution:
events map with capacity equal to len(serials)Code Changes (fetch-events-by-serials.go):
// Pre-allocate map with estimated capacity to reduce reallocations
events = make(map[uint64]*event.E, len(serials))
Problem: Slice created without capacity, causing reallocations during iteration.
Solution:
sers slice with estimated capacity of 100Code Changes (get-serials-by-range.go):
// Pre-allocate slice with estimated capacity to reduce reallocations
sers = make(types.Uint40s, 0, 100) // Estimate based on typical range sizes
Problem: Slice created without capacity, causing reallocations.
Solution:
fidpks slice with exact capacity of len(sers)Code Changes (get-fullidpubkey-by-serials.go):
// Pre-allocate slice with exact capacity to reduce reallocations
fidpks = make([]*store.IdPkTs, 0, len(sers))
Problem: Map created without capacity, causing reallocations.
Solution:
serials map with capacity of ids.Len()Code Changes (get-serial-by-id.go):
// Initialize the result map with estimated capacity to reduce reallocations
serials = make(map[string]*types.Uint40, ids.Len())
Problem: Buffer allocations inside transaction loop, unnecessary nested function.
Solution:
Code Changes (save-event.go):
// Start a transaction to save the event and all its indexes
err = d.Update(
func(txn *badger.Txn) (err error) {
// Pre-allocate key buffer to avoid allocations in loop
ser := new(types.Uint40)
if err = ser.Set(serial); chk.E(err) {
return
}
keyBuf := new(bytes.Buffer)
if err = indexes.EventEnc(ser).MarshalWrite(keyBuf); chk.E(err) {
return
}
kb := keyBuf.Bytes()
// Pre-allocate value buffer
valueBuf := new(bytes.Buffer)
ev.MarshalBinary(valueBuf)
vb := valueBuf.Bytes()
// Save each index
for _, key := range idxs {
if err = txn.Set(key, nil); chk.E(err) {
return
}
}
// write the event
if err = txn.Set(kb, vb); chk.E(err) {
return
}
return
},
)
Problem: Slice created without capacity, causing reallocations.
Solution:
sers slice with estimated capacityCode Changes (save-event.go):
// Pre-allocate slice with estimated capacity to reduce reallocations
sers = make(types.Uint40s, 0, len(idxs)*100) // Estimate 100 serials per index
Problem: Maps created without capacity in batch operations.
Solution:
idHexToSerial map with capacity of len(serials)serialToIdPk map with capacity of len(idPkTs)serialsSlice with capacity of len(serials)allSerials with capacity of len(idPkTs)Code Changes (query-events.go):
// Convert serials map to slice for batch fetch
var serialsSlice []*types.Uint40
serialsSlice = make([]*types.Uint40, 0, len(serials))
idHexToSerial := make(map[uint64]string, len(serials))
// Prepare serials for batch fetch
var allSerials []*types.Uint40
allSerials = make([]*types.Uint40, 0, len(idPkTs))
serialToIdPk := make(map[uint64]*store.IdPkTs, len(idPkTs))
The optimizations implemented should provide the following benefits:
SaveEvent reduces allocations during writes| Function | Optimization | Impact |
|---|---|---|
| QueryForIds | Pre-allocate results, seen map, idPkTs slice | High - Reduces allocations in hot path |
| FetchEventsBySerials | Pre-allocate events map | High - Batch operations benefit significantly |
| GetSerialsByRange | Pre-allocate sers slice | Medium - Reduces reallocations during iteration |
| GetFullIdPubkeyBySerials | Pre-allocate fidpks slice | Medium - Exact capacity prevents over-allocation |
| GetSerialsByIdsWithFilter | Pre-allocate serials map | Medium - Reduces map reallocations |
| SaveEvent | Optimize buffer allocation | Medium - Reduces allocations in write path |
| GetSerialsFromFilter | Pre-allocate sers slice | Low-Medium - Reduces reallocations |
| QueryEvents | Pre-allocate maps and slices | High - Multiple optimizations in hot path |
The codebase already implements batching in several key areas:
bytes.Buffer in FetchEventsBySerials)The optimizations successfully reduced memory allocations and improved efficiency across multiple database operations. The most significant improvements were achieved in:
These optimizations will reduce garbage collection pressure and improve overall application performance, especially in high-throughput scenarios where database operations are frequent. The batching infrastructure was already well-implemented, and the optimizations focus on reducing allocations within those batch operations.