Investigations regarding means to achieve savings in primary energy use and to decrease anthropogenic CO2 emissions have shown that improved energy efficiency has potential to offer a significant contribution to this cause. Considering energy networks and systems, improvements can be achieved by optimizing the structure of the energy chains and distribution networks. For instance, in the case of district heating, it is possible to find an optimal choice of energy supply and design of piping networks to provide the energy required by the customers. Additionally, heat storages and local small-scale energy contributions from e. g. heat pumps could provide benefits and should be taken into consideration. The complexity of the optimization problem increases when the choices of technologies and capacities as well as the network topologies need to be considered. Furthermore, a level of intricacy is added by the large differences in energy demand and temperature conditions between day and night and different seasons. A mixed-integer linear programming model for optimizing distributed energy systems, which takes into account the above mentioned aspects, is being developed and is presented herein. The model is tested with a case study concerning district heating in a locality in southern Finland.