Natural systems at all scales emerge from many components capable of nothing more than simple interactions with their neighbours. This self-organization is one of life’s defining features. As an example, the flagellar motor, one of nature’s most impressive machines, self-assembles from many protein parts to form a tiny nanoscale motor that can spin five times faster than a Formula1 engine. The paradox of molecular assembly is that many protein subunits avoid premature aggregation, yet at the right time self-assemble to form such complex systems. Here we demonstrate that FliG, one of the first motor proteins to assemble, forms ordered ring structures via domain-swap polymerization, which in other proteins has been associated with uncontrolled and deleterious protein aggregation. Solution and crystal structural data, in combination with in vivo biochemical crosslinking experiments and evolutionary covariance analysis, reveal that FliG exists predominantly as a monomer in solution but only as domain-swapped polymers in assembled flagellar motors. We propose a general structural and thermodynamic model for self-assembly, where a structural template controls assembly and shapes polymer formation into rings. This provides a general mechanism by which subunits can assemble into fixed-size rings and reveals the molecular interactions that govern the emergence of complex molecular machinery.