To understand foamy poop, you need to understand lactose and how it is processed. Lactose is the primary sugar in both breast milk and standard infant formula. To digest lactose, your baby's small intestine produces an enzyme called lactase, which breaks lactose down into simpler sugars (glucose and galactose) that can be absorbed into the bloodstream.
Under normal circumstances, lactase handles the lactose load efficiently, and everything gets digested in the small intestine. But when more lactose arrives than the available lactase can process — which is called lactose overload — the undigested lactose passes into the large intestine. Bacteria in the large intestine ferment the undigested lactose, producing gas (carbon dioxide and hydrogen) and organic acids. That gas is what makes the stool foamy. The acids are what can make baby's bottom red and irritated.
The most common reason for lactose overload in breastfed babies is not a deficiency of lactase — it is an excess of lactose arriving too quickly. This happens when baby consumes a disproportionate amount of foremilk, which is higher in lactose and lower in fat. Fat slows gastric emptying, so when baby gets plenty of hindmilk (the fattier milk at the end of a feed), the lactose arrives in the small intestine at a manageable pace. When baby gets mostly foremilk, the lactose rushes through without enough fat to slow it down, overwhelming the lactase.
This is a critical distinction: your baby almost certainly produces enough lactase. The problem is that the lactose is arriving too fast and in too great a quantity for the enzyme to keep up. Fix the feeding mechanics, and the foamy poop typically resolves.