It happened numerous times for me. On Lufthansa flights between Munich and Frankfurt when they used a smaller aircraft with fairly small overhead lockers. It might have been
this model, I used to think of it as the Rabbit Plane because the wings were fixed at the top of the plane and had a negative V shape, like a rabbit's floppy ears. Also on a more recent Iberia flight from Madrid where the ground staff went through the waiting line of passengers at the gate and picked out hand luggage at random that was to be handed over, including my backpack which had clearly smaller dimensions than the suitcases of other passengers some of which looked even larger than the allowed size for cabin luggage.
I was surprised the first time and all the other times I did what others have described already: Quickly removed any items from the backpack that I want to have with me during the flight, like reading glasses etc. It's actually nice that you don't have to take your backpack with you into the cabin, look around to find a space to store it if you are one of those who board towards the end of the process and don't have to wrestle it out of the locker at the end of the flight. You comfortably leave the plane and pick up your backpack at the bottom of the steps.