The sandworms of Arrakis are much like the whales of Earth, albeit with their own enclosed lifecycle & ecosystem. They "swim" through the sands and swallow entire pockets of spice to get at the plankton that dwell within. At the same time, however, the spice is produced by dying worms, which is what feeds the plankton. And the plankton that survive long enough eventually become worms. Dr. Liet Kynes described it thusly:
Now they had the circular relationship: little maker to pre-spice
mass; little maker to shai-hulud; shai-hulud to scatter the spice upon
which fed microscopic creatures called sand plankton; the sand
plankton, food for shaihulud, growing, burrowing, becoming little
When a sandworm swallows a spice pocket, they get their sustenance from the plankton that live within it. The worm then excretes a more refined version of the spice, which is what the plankton eats. This also spreads the spice over the desert, allowing the lifecycle to perpetuate, thus leading to more plankton, more worms, more spice. This knowledge - and the ability to interrupt the cycle - is what gave Paul Atreides his leverage over the universe. Paul and his Fremen secretly planted
a water bomb over one of the major spice pockets. Detonating the bomb would release a large quantity of The Water of Life into the pocket, killing all of the plankton and little makers, causing a chain reaction across the planet which would end all spice production.