Just wondering, at what level this question is asked? Stability in rockets is an old problem that goes back to the pre-WWII days of Goddard, Oberth, von Braun, and the like. Goddard tried putting the engine at the top, and it didn't help. Rockets need active control. That means:
1) Sensors that tell you how far off you are from the desired state. For instance, gyroscopes that sense tilt. The Falcon 9 uses inertial sensors and also GPS.
2) A way to drive and tilt the rocket, with engines and other things. Usually engines are gimbaled these days--they can swing around a few degrees, but also vernier engines (small engines used for guidance), and even vanes in the exhaust stream have been used. The Falcon 9 uses gimbaled engines and cold gas thrusters. It uses grid fins to guide it along the descent path, but those aren't very useful when the speed goes to zero.
3) A brain that connects the two in a feedback loop. It takes information from the sensors, determines the deviation from the desired state, and calculates a corrective action. I have no idea what their control software looks like. The workhorse in industry circles is the PID controller, which produces an output from terms that are Proportional to the deviation, the Integral of it (say the average), and the Derivative, or rate of change. I'm sure SpaceX must use something fancier. For instance, it must model the rocket's behavior so it can predict the future effect of a control effort now, rather than just tracking a present-time deviation.
And all of that basically to do what you do intuitively when you walk around with a broom balanced on a finger. If the broom starts to tilt, you can see it and feel it, and you move your finger to catch it.
Here is a video that talks about some of it, but not in the detail that I would have liked.