By creating a society that, on balance, trusts the state and it's institutions to enact justice (apply suffering, in context).
It will fail to be perfect, same as any other system. But it just needs to work well enough that a sufficient mass of citizens don't lose faith in it and try to enact their own forms of justice.
We can all point to cases where murderers got away with it, or someone who was ruled guilty received a sentence we think is wrong, but _overall_, we're ok with the state managing violence on our behalf.
> In terms of practical social functioning, rehabilitation of criminals is much more valuable than punishment, which is why most democracies at least aspire to this ideal.
There is little evidence that any rehabilitation schemes are particularly successful, with the gaps between the most- and least- effective not being particularly meaningful.
You prevent crimes by removing people that commit them from society.