GO:0010960: magnesium ion homeostasis
Any process involved in the maintenance of an internal steady state of magnesium ions within an organism or cell.