A custard thickened only with eggs turns grainy if it gets too hot, while a pastry cream is boiled deliberately. The difference is starch, and what it does to the proteins around it.

Egg proteins set within a narrow window

Heating egg proteins causes them to unfold and bond to one another, trapping the surrounding liquid in a soft gel.

Held gently, that network stays fine and even, which is what gives a properly cooked custard its smooth body.

Pushed hotter, the proteins keep bonding and contract into tight clumps, squeezing liquid out. That is curdling, and it is simply overcooking made visible.

Dilution and sugar widen the window

Milk and cream separate the protein molecules from one another, so they take longer to find partners and set at a higher temperature than plain egg does.

Sugar has a similar effect, getting between the proteins and raising the point at which the network forms.

This is why a sweet, dairy-rich custard is more forgiving than a lean one, and why reducing the sugar in such a recipe makes it harder to cook rather than merely less sweet.

Starch changes the rules entirely

Starch granules absorb water and swell as they heat, thickening the mixture and physically separating protein molecules from each other.

That interference prevents the tight bonding that causes curdling, so a starch-thickened custard can be brought to a boil without breaking.

Boiling is in fact necessary, because raw flour or cornflour tastes of itself and needs cooking out, and because full thickening only occurs at high temperature.

Egg yolks contain an enzyme that undoes the work

Yolks carry an enzyme that breaks down starch, and if a starch-thickened custard is left undercooked that enzyme thins it again as it stands.

Heat destroys the enzyme, which is another reason pastry cream is boiled briefly rather than merely thickened.

A custard that sets well and then turns runny in the refrigerator was almost certainly not taken hot enough for long enough.

Technique compensates for the chemistry

Tempering, which means adding hot liquid to the eggs gradually before returning everything to the pan, avoids dropping cold eggs into a hot mass where they set instantly.

Constant stirring keeps any part of the mixture from sitting against the hot base long enough to exceed the setting range.

A curdled custard caught early can sometimes be rescued by blending or straining, which breaks up the clumps even though the smooth gel is gone for good.