A good starting point may be to look at the (very crude) BTreeDB5 writing logic in the repair.py script.
We need to do reasonably well at packing leaves, balancing the tree (indexes), and managing free blocks to not adversely affect gameplay on the world.