They use the Facebook Pixel https://www.facebook.com/business/a/facebook-pixel
They segment users that visited each product on Facebook with a custom audience and then create ads for similar products that they show you. This is all done programmatically.