We study optimal synchronization in networks of heterogeneous phase oscillators. Our main result is the derivation of a synchrony alignment function that encodes the interplay between network structure and oscillators' frequencies and that can be readily optimized. We highlight its utility in two general problems: constrained frequency allocation and network design. In general, we find that synchronization is promoted by strong alignments between frequencies and the dominant Laplacian eigenvectors, as well as a matching between the heterogeneity of frequencies and network structure.