I can recommend a couple of off-the-shelf options for N scale installs where space is at a premium.
My current favourite is the TCS KA-N1
https://www.tcsdcc.com/product-page/ka-n1These are the smallest commercially available keep alive circuits that I've come across at only 6.6mm x 9.2mm x 3.5mm. I use these in a 3D printed holder for my Scale Trains Dash 9s where there is very limited clearance above the motor universal shafts:
(photo was taken before wires terminated and Kapton tape added).
I also have a large number of the Iowa Scale Engineering Run-N-Smooth Power Keepers
https://www.iascaled.com/store/ModelRailroad/Run-N-Smooth/CKT-DCCSAThese work great where there is a bit more room for the install (9.1mm x 10.4mm x 4.65mm).
ISE Run-N-Smooth installed in the milled front-upper section of a Kato SD40-2 Mid Production (fits under an ESU 58741 Kato drop-in decoder):
ISE Run-N-Smooth installed in the milled fuel tank of Kato SD40-2 Early:
With only 940-100 microFarads, these options might not seem sufficient, but my experience with operations and sound is that they make a significant improvement to reliability.
On relatively clean track and turnouts with powered frogs, sound dropouts become almost non-existent. For four axle locos and sound, a keep alive really is a must. I can run up and down yard ladders all day without any annoying sound drop outs.
Hope this info helps. Cheers