Prateek
Prateek

Reputation: 429

Debugging Twilio SSL Errors (Error 11220) that are fixed by Server Restart

I have a basic rest api server that accepts incoming sms'es and replies using the Twilio api. Every two months or so I've noticed I need to restart the server because Twilio starts giving me SSL Handshake errors. It's not anything to do with the https certificate because as I mentioned it is fixed by a simple restart. I'm looking for help debugging this.

Structure of the tool

app.py - FastApi Rest Server. There's a /webhook endpoint to accept Twilio incoming messages requests.

utils.py - Utils file that has the method used to send Sms via Twilio api.

TWILIO_CLIENT = Client(TWILIO_SID, TWILIO_AUTH_TOKEN)

async def send_twilio_sms(twilio_message: TwilioMessage):
    """
    Send the message via twilio
    """
    try:
        ph_number = twilio_message.phone_number
        message = twilio_message.message
        msg = TWILIO_CLIENT.messages.create(to=ph_number,
                                            messaging_service_sid=TWILIO_MESSAGING_SERVICE_SID,
                                            body=message)
    except TwilioRestException as e:
        raise
    return msg, msg.sid

The actual server is pretty basic as well with uvicorn sudo ~/.pyenv/versions/myproject/bin/uvicorn app:app --port xxxx --host 0.0.0.0 --ssl-keyfile=/etc/letsencrypt/live/myprojectdomain/privkey.pem --ssl-certfile=/etc/letsencrypt/live/myprojectdomain/fullchain.pem

Upvotes: 1

Views: 416

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67509

You haven't included the most important piece of information in your question, which is the actual log with the SSL errors. So I'm going to make a best guess.

Let's Encrypt certificates need to be renewed every three months. My assumption is that you have a cron job, timer or similar that runs certbot periodically to renew any certificates that are closer to their expiration date. The renewal is pretty much transparent, the fullchain.pem file is just updated in place.

So in the best of situations, you will need to restart uvicorn once every three months, just so that it reloads the certificate. Have a look at the --post-hook option of the certbot renew command: https://certbot.eff.org/docs/using.html?highlight=hook#renewing-certificates. This allows you to add a custom command after the certificate is renewed. You will use this to send a signal to your uvicorn process to reload or restart.

Also, this is unrelated to your question, but you should know that the Twilio libraries are blocking under asyncio, so you should run any functions that make calls to Twilio APIs in an executor or other method that prevents the async loop from blocking. My Using the Twilio Python Helper Library in your Async Applications article on the Twilio blog will give you a list of options that you have.

Upvotes: 2

Related Questions