Year and model?
There are a few things that can cause this, but I had to replace the ECU on a 540 to cure these same symptoms once, while a different car had these symptoms and the cause was something obstructing the throttle body.

I have not had that problem with a customer car, but there is a simple tool that checks the back pressure by screwing it in place of the front O2 sensor and running the car. You will probalby need to take it to a shop to diagnose it. I always recommend qualified independents.