Its good you keep playing this over and over in your mind so you can learn from it. Its easy to be a Monday morning quarterback, but some things you could take away from this is to keep your phone in your hands, not your gun. I'd also have the camera ready to record quickly. After the 2nd encounter, especially involving a knife/weapon, call 911. Also, alleys are pretty notorious for "trouble" and since youve had 2 disturbing encounters, I would avoid that alley if possible. I see many folks walking their dogs, or just simply walking and the majority of them have a walking stick. I'm sure they carry it in case they encounter other dogs, but that stick could come in real handy. I'd also consider carrying pepper spray.
As mentioned, along with carrying a gun comes a ton of responsibility. I dont think I would have threaten to pull it, or show it to him in an attempt to resolve this particular situation as you described. Once a gun is pulled, the situation is at its highest and will end by either shooting the weapon, potentially killing this man, or you re-holster. Both of these choices come with their own consequences. Dont ever take either one lightly. That guy could call the cops and claim you were trying to rob him at gunpoint and the burden would be on you to prove otherwise. And chances are the 1st guy you encountered would likely be a witness for the other guy. Again, maybe not "right", but I would avoid that alley in the future.
I would have absolutely called the cops after the 2nd altercation. I mean, the guy "pulled a knife" on you and THAT needs to be reported. I'm glad you came out of it unharmed.