Changes in the sequence of an organism's genome, i.e. mutations, are the raw material of evolution 1 . The frequency and location of mutations can be constrained by specific molecular mechanisms, such as Diversity-generating retroelements (DGRs) 2-4 . DGRs introduce mutations in specific target genes, and were characterized from several cultivated bacteria and bacteriophages 2 . Whilst a larger diversity of DGR loci has been identified in genomic data from environmental samples, i.e. metagenomes, the ecological role of these DGRs and their associated evolutionary drivers remain poorly understood 5-7 . Here we built and analyzed an extensive dataset of >30,000 metagenome-derived DGRs, and determine that DGRs have a single evolutionary origin and a universal bias towards adenine mutations. We further identified six major lineages of DGRs, each associated with a specific ecological niche defined as a genome type, i.e. whether the DGR is encoded on a viral or cellular genome, a limited set of taxa and environments, and a distinct type of target. Finally, we leverage read mapping and metagenomic time series to demonstrate that DGRs are consistently and broadly active, and responsible for >10% of all amino acid changes in some organisms at a conservative estimate. Overall, these results highlight the strong constraints under which DGRs diversify and expand, and elucidate several distinct roles these elements play in natural communities and in shaping microbial community structure and function in our environment. 2 30 35 40 45 50 55 60 65 70Here we expand the set of known DGRs ~15-fold by extracting 31,007 DGRs from public metagenomes and metatranscriptomes to obtain a holistic view of DGR diversity and their spatial and temporal dynamics. We leverage this comprehensive collection to (i) evaluate the global ecology and evolution of DGRs across viral and cellular genomes, (ii) characterize the functional diversity and molecular constraints of DGR targets, and (iii) infer temporal patterns of DGR activity across organisms and biomes. Taken together, these analyses reveal how DGRs are frequently transferred between genomes yet clearly restricted to specific ecological niches, within which they likely impact both viral and microbial dynamics by consistently driving amino acid-level diversification of their target domains.