You should apply at least 3 days prior to your arrival. However, since the ESTA is valid for 2 years, it is recommended that you apply as soon as you are able.