In order to stay upright, your body is sensing the direction of the sway and activating the muscles on the opposite side of the body to contract and correct your upright position. Your muscles and joints "know" where they are in space. This process, which is called proprioception, happens at lightening speed without your consciously thinking about it. Proprioception is the ability of our bodies to detect where we are in space (i.e., whether we are leaning to the right or left) and to contract muscles appropriately for us to stay upright.
There are actually many systems working together to keep us standing upright. Balancing effectively takes our eyes, ears (vestibular system), and peripheral sensory system (skin receptors of pressure and touch) as well as our neuromuscular connections (the nerve pathways between our brains and muscles, tendons, ligaments, and joints). Our brains are able to coordinate these signals to determine where our limbs are in space and the speed and direction of their movement.