The general idea is potassium is actively pumped into the lumen of Malpighian tubules. Water accompanies this movement, along with some amounts of other salts, and there is a concomitant bulk flow into hindgut and thence to rectum. Before the water is voided, salts are again actively pumped back into the extracellular compartment by specialized regions of rectum. This second pumping of ions produces a very dilute urine which can be voided while ions are kept within bodies. Recall that salts are lost across cuticles and, to lesser extent, in urine.
Insects living in fresh water, then, actually have two problems.
First, they must produce copious amounts of dilute urine so that extracellular fluid compartments are not diluted by incoming water. Second, they must somehow replace salts that are inevitably lost, also to keep extracellular compartments from becoming too dilute. Some salts will be gained from food, but in addition to this, some aquatic larvae are able to take up salts from very dilute solutions in the water they live in. Larvae of the dipteran genera Aedes , Culex and Chironomus take up salts though specialized structures called anal papillae, also known as anal gills. This uptake requires energy expenditure.