As goldfish are mostly vegetarian by nature, they have a long gut to digest high-fibre foods. Although a diet based on dry food has all the vitamins and minerals to keep a fish in good condition, it can lack the fibre needed to ensure a healthy digestive tract and this means that slow-moving food generates gas as it passes through the gut, affecting natural buoyancy. By giving your goldfish frozen fish foods and access to plant material, you can make sure that your pet remains healthy inside and out.
To avoid other buoyancy issues with goldfish, it may be better to offer a pellet food to limit the amount of air that feeding fishes can swallow when taking food at the surface.
Historically, this syndrome has been referred to as 'swimbladder disease' and it's true that various internal infections can produce gases that will lead to the same symptoms. Together with an improved diet, treatment with an anti internal bacteria product would be wise. If symptoms persist, it may indicate a more complex health issue.