It's not the red lines disappearing that determines whether or not you get hit.
If you are inside the red lines at the end of the spell cast you are going to get hit !!!!!!

Yes there are times that lag or whatever occurs that affect this, which isn't SE's fault.

And yes they could have coded it better so the red lines disappear at the end of the spell cast, which is SE's fault.

But it is what it is, move out of the red before the cast bar reaches 100% and you'll get hit less often.