Bousfield-Kan completion as a codensity $\infty$-monad
Working in the setting of $\infty$-categories, we develop a general theory of the codensity monad $T_\mathcal{D}$ associated with a full subcategory $\mathcal{D}\subseteq \mathcal{C}$. We show that $T_\mathcal{D}$ has a canonical monad structure (unique up to a contractible space of choices), and characterize it as a terminal monad preserving all objects of $\mathcal{D}$. For a monad $\mathcal{M}$ on an $\infty$-category $\mathcal{C}$, we consider the $\mathcal{M}$-completion functor defined as the totalization of the cosimplicial resolution associated with $\mathcal{M}$. We show that the $\mathcal{M}$-completion functor is the codensity monad associated with the full subcategory of $\mathcal{C}$ spanned by objects that admit a structure of $\mathcal{M}$-algebra. In particular, the $\mathcal{M}$-completion functor is the terminal monad preserving all objects that admit a structure of an $\mathcal{M}$-algebra. This gives a full $\infty$-categorical characterization of the classical Bousfield-Kan $R$-completion functor as the terminal monad on the category of spaces preserving the empty space and all products of Eilenberg-MacLane spaces $K(A,n)$, where $A$ is an $R$-module.