I noticed this happens when the required resources (for an upgrade) are very close to the displayed available resources. The bug is very likely caused by a discrepancy between the displayed amounts and the real resource amounts on the server. It looks to me that upgrades happen like this:
1. If the displayed amounts are enough for the upgrade, allow the upgrade;
2. When the player pushes the upgrade button, the client (in-browser-game) checks if the amount of resources are available and if they are, it sends the server two commands:
2.1 Deduct resources Y and Z from the player's account;
2.2 Upgrade building X;
3.1 The server executes 2.1 and deducts the resources from the account
3.2 The server checks for the actual resources (on-server) and if they exist it will upgrade, and if not... no upgrade.
Assuming I'm right, there are two sides of this bug:
1. The server should check for resources before anything, and only initiate an upgrade if the resources are available, deducting the resources only if the upgrade succeeded.
2. The server should reject upgrades if there are not enough resources and forbid the client to deduct the resources from the displayed values.
I might be wrong about these details, but I don't remember seeing the issue when I had an excess of resources when I upgraded something. So in conclusion, the safest way to prevent this bug from showing up is to be patient to gather resources well over the displayed amount, just so you don't get hit by the discrepancy bug (weird conditions in the code).