Grounding systems are critical in safeguarding people and equipment from power system failures. A grounding system's principal goal is to offer the lowest impedance path for undesired fault current. Optimization of the grounding grid designs is important in satisfying the minimum cost of the grounding system and safeguarding those people who work in the surrounding area of the grounded installations. Currently, there is no systematic guidance or standard for grounding grid designs that include two-layer soil and its effects on grounding grid systems, particularly vertically layered soil. Furthermore, while numerous studies have been conducted on optimization, relatively limited study has been done on the problem of optimizing the grounding grid in two-layer soil, particularly in vertical soil structures. This paper presents the results of optimization for substation grounding systems using the Simulated Annealing (SA) algorithm in different soil conditions which conforms to the safety requirements of the grounding system. Practical features of grounding grids in various soil conditions discussed in this paper (uniform soil, two-layer horizontal soil, and two-layer vertical soil) are considered during problem formulation and solution algorithm. The proposed algorithm's results show that the number of grid conductors in the X and Y directions (Nx and Ny), as well as vertical rods (Nr), can be optimized from initial numbers of 35% for uniform soil, 57% for horizontal two-layer soil for ρ1> ρ2, and 33% for horizontal two-layer soil for ρ1< ρ2, and 29% for vertical two-layer soil structure. In other words, the proposed technique would be able to utilize square and rectangle-shaped grounding grids with a number of grid conductors and vertical rods to be implemented in uniform, two-layer horizontal and vertical soil structure, depending on the resistivity of the soil layer.