The functions of many microbial communities exhibit remarkable stability despite fluctuations in the compositions of these communities. To date, a mechanistic understanding of this function–composition decoupling is lacking. Statistical mechanisms have been commonly hypothesized to explain such decoupling. Here, we proposed that dynamic mechanisms, mediated by horizontal gene transfer (HGT), also enable the independence of functions from the compositions of microbial communities. We combined theoretical analysis with numerical simulations to illustrate that HGT rates can determine the stability of gene abundance in microbial communities. We further validated these predictions using engineered microbial consortia of different complexities transferring one or more than a dozen clinically isolated plasmids, as well as through the reanalysis of data from the literature. Our results demonstrate a generalizable strategy to program the gene stability of microbial communities. Dynamic redundancy by horizontal gene transfer stabilizes gene abundances amidst compositional fluctuations in microbial communities, which suggests a means to program gene stability of complex microbiota.